python - 如何使用聚合旋转或转置部分数据帧
问题描述
我有一个数据框df
,其中 5 列的组合:item, fav_topping, cheese, crust, order_yr_month
是唯一的。有 1450 行。
item fav_topping cheese crust order_yr_month #_of_orders
0 Pizza Pineapple PPJ Thin 2020-12 0
1 Pizza Pineapple PPJ Thick 2021-01 0
2 Pizza Pineapple PPJ Thin 2021-02 0
3 Pizza Pineapple PPJ Thick 2021-03 0
4 Pizza Pineapple PPJ Pan 2021-04 9
... ... ... ... ... ... ...
1446 Sandwich Pickles CHD Pan 2022-07 91
1447 Sandwich Pickles CHD Thick 2022-08 91
1448 Sandwich Pickles CHD Thin 2022-09 11
1449 Sandwich Pickles CHD Cheese 2022-10 12
1450 Sandwich Pickles CHD Cheese 2027-12 0
我想将其转换为result_df
需要导出的 excel,其中唯一order_yr_month
需要转置并且#_of_orders
必须聚合。请注意,行数 (65) 现在只有 4 列的唯一组合item, fav_topping, cheese, crust
item fav_topping cheese crust 2020-12 2021-01 2021-02 2021-03 2021-04 2022-07 2022-08 2022-09 2022-10
0 Pizza Pineapple PPJ Thin 0 0 0 0 0 0 0 0 0
1 Pizza Pineapple PPJ Thick 0 0 0 0 0 0 0 0 0
2 Pizza Pineapple PPJ Cheese 0 0 0 0 0 0 0 0 0
3 Pizza Pineapple PPJ Roast 0 0 0 0 0 0 0 0 0
4 Pizza Pineapple PPJ Pan 0 0 0 0 9 0 0 0 0
... ... ... ...
61 Sandwich Pickles CHD Pan 0 0 0 0 0 91 0 0 0
62 Sandwich Pickles CHD Thick 0 0 0 0 0 0 91 0 0
63 Sandwich Pickles CHD Thin 0 0 0 0 0 0 0 11 0
64 Sandwich Pickles CHD Cheese 0 0 0 0 0 0 0 0 12
65 Sandwich Pickles CHD Roast 0 0 0 0 0 0 0 0 0
熊猫这样做的方式是什么?
我的尝试都失败了:
- 在部分表上使用 pivot_table?
- 使用转置
- 使用多索引
- 提取子表
index, order_yr_month, #_of_orders
,然后转置它们。- 这里的问题是年月列是唯一的,result_df
但并非所有行都df
具有所有这些列。
更新:
@jezrael 在阅读交叉表文档后向我指出了正确的 解决方案-
这是有效的 -
result_df = pd.crosstab(index=[df['item'],df['fav_topping'],df['cheese'],df['crust']], columns=df['order_yr_month'], values=df['orders'], aggfunc='sum')
解决方案
推荐阅读
- android - “定时发布”中的“开始部署到生产”按钮有什么作用
- javascript - 如何使用正则表达式设置文本小写?
- python - 如何将字典转换为数据框?
- oracle - 如何从oracle中的语句中替换多个单词/特殊字符
- java - 在不控制底层协议的情况下确保套接字连接
- vba - 通过宏重新启动 PowerPoint 演示文稿
- amcharts - AmCharts如何防止数据标签溢出?
- google-cloud-platform - GKE 上的 Knative 无法处理某些图像,显示 RevisionMissing 错误
- c# - 如何修复 JPG 文件中的 EXIF 方向数据
- node.js - 我如何将 jsdoc 参数发送到 Web 请求?