熊猫:取消融化数据框以添加任意数量的列?

时间:2019-11-26 12:42:30

标签: python pandas

我在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

如何在熊猫中做到这一点?

我认为这是stores列上的一种枢纽,但有多个。还是这是“解开”而不是“枢轴”?

我尝试过:

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

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

1 个答案:

答案 0 :(得分:4)

使用DataFrame.unstack进行重塑,仅需通过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