gpt4 book ai didi

python - Pandas :取消融化数据框以添加任意数量的列?

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:13 25 4
gpt4 key购买 nike

我在 Pandas 中有一个数据框 df,如下所示:

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

我如何在 pandas 中执行此操作?

我认为这是 stores 列的某种支点,但有多个 .或者它可能是“未熔化”而不是“枢轴”?

我试过:

df.pivot("stores", ["product", "discount"], ["product", "discount"])

但我得到 TypeError: MultiIndex.name must be a hashable type

最佳答案

使用DataFrame.unstack对于 reshape ,只需要通过 GroupBy.cumcount 创建计数器, 最后更改第二层的排序并通过 map 展平列中的 MultiIndex:

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

关于python - Pandas :取消融化数据框以添加任意数量的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com