首页 > 解决方案 > 熊猫:解开数据框以添加任意数量的列?

问题描述

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

标签: pythonpandas

解决方案


用于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  

推荐阅读