python - 如何在数据框中为 groupby 做 Python
问题描述
我有一个包含交易的数据框。我想对数据进行分组。
buy_date category subcategory product actual_price sell_price
1/1/2021 Cloth women shirt style A 5 4
1/1/2021 Cloth men skirt style A 7 6.5
1/1/2021 Accessories ear sky wing 2 1
2/1/2021 Automotive wheel small 21 18
2/1/2021 Automotive wheel big 34 30
1/14/2021 Accessories ring queen couple 3 3
1/17/2021 Cloth women shirt style B 7 7
1/17/2021 Cloth men skirt style A 7 6.5
4/2/2021 Cloth men skirt style A 10 9
5/2/2021 Accessories ring queen couple 3 2.5
7/2/2021 Cloth women shirt style B 16 12
7/2/2021 Automotive wheel big 40 35
2/26/2021 Accessories ring queen couple 4 4
2/26/2021 Cloth women shirt style B 9 5
2/26/2021 Cloth men skirt style A 7 9
2/28/2021 Accessories ear sky wing 2 1
1/3/2021 Automotive wheel big 38 35
1/3/2021 Accessories ring queen couple 4 4
7/3/2021 Automotive wheel big 39 37
3/31/2021 Accessories ring queen couple 4 4
我想获得每个类别和子类别的平均每月销售量和实际价格。我尝试了很多方法,但它们都无法正常工作。谢谢
解决方案
做就是了:
>>> df.groupby(['category', 'subcategory']).mean()
actual_price sell_price
category subcategory
Accessories ear 2.00 1.00
ring 3.60 3.50
Automotive wheel 34.40 31.00
Cloth men 7.75 7.75
women 9.25 7.00
>>>
推荐阅读
- javascript - 为什么在 Node.js 中使用 async-await 时会丢失堆栈跟踪?
- angular - 单击事件在 IE 10 中有效,但在 IE 11 中无效
- content-security-policy - CSP 严格动态信任未传播
- c# - SqlException:无法打开登录请求的数据库“DB_NAME”。登录失败
- angular - 错误 TS2339:“主题”类型上不存在属性“startWith”
' - javascript - 在 JavaScript 中按索引大小排序
- c# - 进入打印预览时如何删除表单的按钮
- algorithm - 如何在 O(n^2) 时间内实现 Convex Hull 的在线构建?
- c# - 使用 GetFileFromApplicationUriAsync 获取 json 文件时出现“值不在预期范围内”异常
- python-3.x - 如何使用 GPU 运行张量流?