大Pandas连续变量的动态装箱

2024-04-20 07:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下熊猫数据帧

   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

我怎样才能在熊猫身上做到呢?你知道吗


Tags: 数据indexquantitybins
1条回答
网友
1楼 · 发布于 2024-04-20 07:31:58

这是你需要的吗?你知道吗

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

相关问题 更多 >