Ranjan Mondal
Ranjan Mondal

Reputation: 19

How to bin data in data frame in pandas

I have a time series data, say machine reading as follows(Say)

df['machine_r'] = [1,2,1,5,3,4,5,1,2,3,4,5,7,8,1,2.....] 

How to change the data frame like following

If data in dataframe <= 25 percentile, value = 0.25, 
if 25p < data <=50p  value =  0.50,
if 50p<data <= 75p, value = 0.75,
if data>75p , value = 1

I have tried

p25 = df['machine_r'].quantile(0.25)  ## p25 is 25 percentile 
p50 = df['machine_r'].quantile(0.5)
p75 = df['machine_r'].quantile(0.8)
p100 = df['machine_r'].quantile(1)
bins = [-100,p25,p50,p75,p100]
labels = [0.25, 0.5,0.75,1]
df['machine_r'] = pd.cut(df['copper'], bins=bins,labels=labels)

but it is returning 0, 0.25, 0.5, 0.75, 1 as categorical values but I need them as float for further analysis. How can it be done?

Upvotes: 1

Views: 1044

Answers (1)

jezrael
jezrael

Reputation: 862581

You can cast it to float by astype:

df['new'] = pd.cut(df['machine_r'], bins=bins,labels=labels).astype(float)

Also better is use qcut like mentioned Sandeep Kadapa:

df['new'] = pd.qcut(x=df.machine_r, q=[0, .25, .5, .8, 1.], labels=labels).astype(float)
print (df)
    machine_r   new
0           1  0.25
1           2  0.50
2           1  0.25
3           5  0.75
4           3  0.50
5           4  0.75
6           5  0.75
7           1  0.25
8           2  0.50
9           3  0.50
10          4  0.75
11          5  0.75
12          7  1.00
13          8  1.00
14          1  0.25
15          2  0.50

print (df.dtypes)
machine_r      int64
new          float64
dtype: object

Upvotes: 1

Related Questions