python - 根据为 value_counts 指定的 bin 对另一列执行聚合
问题描述
假设我有一个带有两列的 Pandas 数据框。df.Price
和df.Revenue
。我可以执行df.Price.value_counts(bins=[5,10,15])
并确定 3 个箱中的每个箱中的价格数量。
但是,我想知道我为Price
列指定的那些箱中的总收入是多少。我如何实现这一目标?对此的扩展是找出每个垃圾箱的交易数量(计数)?
解决方案
用于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
推荐阅读
- azure-devops - 从逻辑应用向 Azure DevOps 进行身份验证
- javascript - 为什么 webpack 加载多个 app.js 文件而不是单个 app js 文件
- php - PHP在字符串参数中使用“字符
- javascript - 渲染 2 个函数(学习最佳实践)
- kotlin - 如何使用 ViewModelProviders.of() 访问 Activity 中的 ViewModel?
- javascript - Angular ng-content 隐藏某些元素
- pyspark - 将各种日期格式转换为 pyspark 中的通用日期格式
- ios - TableView 内单元格中照片的大小
- java - 如何在java中压缩一组给定的文件
- linux - 如何通过shell脚本从目录名称中删除特定前缀