How to make each bin of data as column of dataframe

Viewed 78

I have have dataframe with column A , i want to divide column in bins and count of each bin as column of dataframe , for example bin from 0 to how many points and add this in in dataframe.

i used this code for binning but i am not sure how to insert count column in df.

df=pd.DataFrame({'max':[0.2,0.3,1,1.5,2.5,0.2]})
print(df)
   max
0  0.2
1  0.3
2  1.0
3  1.5
4  2.5
5  0.2

    bins = [0, 0.5, 1, 1.5, 2, 2.5]

    x=pd.cut(df['max'], bins)

desired output

print(df)
   0_0.5_count  0.5_1_count
0            3            1
1 Answers

First add parameter label to cut, then count by Series.value_counts and for DataFrame use Series.to_frame with transpose by DataFrame.T:

bins = [0, 0.5, 1, 1.5, 2, 2.5]

labels = ['{}_{}_count'.format(i, j) for i, j in zip(bins[:-1], bins[1:])] 
x=pd.cut(df['max'], bins, labels=labels).value_counts().sort_index().to_frame(0).T
print (x)

   0_0.5_count  0.5_1_count  1_1.5_count  1.5_2_count  2_2.5_count
0            3            1            1            0            1

Details:

print (pd.cut(df['max'], bins, labels=labels))
0    0_0.5_count
1    0_0.5_count
2    0.5_1_count
3    1_1.5_count
4    2_2.5_count
5    0_0.5_count
Name: max, dtype: category
Categories (5, object): [0_0.5_count < 0.5_1_count < 1_1.5_count < 1.5_2_count < 2_2.5_count]

print (pd.cut(df['max'], bins, labels=labels).value_counts())
0_0.5_count    3
2_2.5_count    1
1_1.5_count    1
0.5_1_count    1
1.5_2_count    0
Name: max, dtype: int64  

Alternative solution with GroupBy.size:

bins = [0, 0.5, 1, 1.5, 2, 2.5]

labels = ['{}_{}_count'.format(i, j) for i, j in zip(bins[:-1], bins[1:])] 
x= df.groupby(pd.cut(df['max'], bins, labels=labels)).size().rename_axis(None).to_frame().T
print (x)
   0_0.5_count  0.5_1_count  1_1.5_count  1.5_2_count  2_2.5_count
0            3            1            1            0            1
Related