python - 熊猫:解开数据框以添加任意数量的列?
问题描述
我df
在 Pandas 中有一个如下所示的数据框:
stores product discount
Westminster 102141 T
Westminster 102142 F
City of London 102141 T
City of London 102142 F
City of London 102143 T
我想最终得到一个如下所示的数据集:
stores product_1 discount_1 product_2 discount_2 product_3 discount_3
Westminster 102141 T 102143 F
City of London 102141 T 102143 F 102143 T
我如何在熊猫中做到这一点?
我认为这是列上的某种支点stores
,但有多个 . 或者也许它是一个“未融化”而不是一个“枢轴”?
我试过了:
df.pivot("stores", ["product", "discount"], ["product", "discount"])
但我明白了TypeError: MultiIndex.name must be a hashable type
。
解决方案
用于DataFrame.unstack
重塑,只需要创建计数器GroupBy.cumcount
,第二级的最后更改排序并在列中展平 MultiIndex map
:
df = (df.set_index(['stores', df.groupby('stores').cumcount().add(1)])
.unstack()
.sort_index(axis=1, level=1))
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
df = df.reset_index()
print (df)
stores discount_1 product_1 discount_2 product_2 discount_3 \
0 City of London T 102141.0 F 102142.0 T
1 Westminster T 102141.0 F 102142.0 NaN
product_3
0 102143.0
1 NaN
推荐阅读
- memory-leaks - 带有静态 HTML 的 IE 11 内存泄漏,没有 JS
- python - wx中不同弹出选择的不同matlibplots
- c# - c#中图片框中单击的坐标
- visual-studio-code - Angular 语言服务在一个项目中工作,但不在另一个项目中
- c# - 无法从 kubernetes 中的 c# 前端连接到 Mysql 服务
- visual-studio-code - 在 vscode 中使用 pug 时如何隐藏 html 输出文件?
- database - 如何为一个dolphindb数据节点配置多个硬盘
- javascript - getDerivedStateFromProps,改变props影响下的状态改变
- excel - 比较两张纸以匹配值并将匹配的一张粘贴到第三张
- c# - 如何修复asp net mvc中图片的链接