根据为value_counts指定的bin为另一列执行一列的聚合

时间:2018-05-18 21:22:49

标签: python pandas

假设我有两个列的Pandas数据帧即可。 df.Pricedf.Revenue。我可以执行df.Price.value_counts(bins=[5,10,15])并确定3个箱子中每个箱子的价格数量。

但是,我想知道我为Price列指定的那些垃圾箱中的总收入是多少。我该如何实现这一目标?对此的扩展是找出每个箱的交易数量(计数)?

1 个答案:

答案 0 :(得分:1)

使用pd.cut创建一个包含bucketing的虚拟列,然后将其分组。

>>> df = pd.DataFrame({'Price': np.random.randint(0,20,(10,)), 
                       'Revenue': np.random.rand(10)})
>>> df
   Price   Revenue
0      0  0.104462
1      9  0.976338
2      7  0.800895
3     13  0.700494
4     13  0.241352
5      0  0.535348
6     13  0.811419
7     17  0.508165
8     13  0.580809
9      5  0.711055

>>> df['Bucket'] = pd.cut(df['Price'], [-float('inf'), 5, 10, 15, float('inf')])
>>> df
   Price   Revenue        Bucket
0      0  0.104462   (-inf, 5.0]
1      9  0.976338   (5.0, 10.0]
2      7  0.800895   (5.0, 10.0]
3     13  0.700494  (10.0, 15.0]
4     13  0.241352  (10.0, 15.0]
5      0  0.535348   (-inf, 5.0]
6     13  0.811419  (10.0, 15.0]
7     17  0.508165   (15.0, inf]
8     13  0.580809  (10.0, 15.0]
9      5  0.711055   (-inf, 5.0]

>>> df.groupby('Bucket').sum()
              Price   Revenue
Bucket                       
(-inf, 5.0]       5  1.350865
(5.0, 10.0]      16  1.777233
(10.0, 15.0]     52  2.334075
(15.0, inf]      17  0.508165

>>> df.groupby('Bucket')['Revenue']
      .agg(['count', 'sum'])
      .rename(columns={'sum': 'Net Revenue'})                                                              
              count  Net Revenue
Bucket                          
(-inf, 5.0]       3     2.266008
(5.0, 10.0]       3     1.477182
(10.0, 15.0]      1     0.432358
(15.0, inf]       3     2.097361
相关问题