首页 > 解决方案 > pandas中连续变量的动态分箱

问题描述

我在熊猫中有以下数据框

   Index    Quantity
   1        12
   2        23
   3        24.45
   4        0.56
   5        100.23
   6        50.45

我想要的数据框是

   Index    Quantity      bins
   1        12            10-14.99 
   2        23            20-24.99
   3        24.45         20-24.99
   4        0.56          0-4.99
   5        100.23        100-104.99
   6        50.45         50-54.99

我怎样才能在熊猫中做到这一点?

标签: pythonpandas

解决方案


这是你需要的吗?

s1=((df.Quantity//5)*5).min()
s2=((df.Quantity//5+1)*5).max()
s1
Out[527]: 0.0
s2
Out[528]: 105.0
pd.cut(df.Quantity,np.arange(s1,s2+5,5))
Out[529]: 
0      (10.0, 15.0]
1      (20.0, 25.0]
2      (20.0, 25.0]
3        (0.0, 5.0]
4    (100.0, 105.0]
5      (50.0, 55.0]
Name: Quantity, dtype: category

推荐阅读