首页 > 解决方案 > 根据为 value_counts 指定的 bin 对另一列执行聚合

问题描述

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

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

标签: pythonpandas

解决方案


用于pd.cut创建一个包含分桶的虚拟列,然后对其进行分组。

>>> 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

推荐阅读