在 python 中创建自定义数据转置

create customized transpose of data in python

我有这样一个数据框:

ID  Month   Price   Sale
sk1 1       100     6
sk1 2       120     7
sk1 3       130     8
sk2 1       50      3
sk2 2       60      4
sk2 3       70      5

期望的输出:

ID  1_Price 2_Price 3_Price 1_Sale  2_Sale  3_Sale
sk1 100     120     130     6       7       8
sk2 50      60      70      3       4       5

我尝试 pandas 使用索引选项进行转置,但没有给出预期的结果。

使用 set_index with unstack or pivot,然后按 list comprehension:

将列中的 MultiIndex 展平
df = df.set_index(['ID','Month']).unstack()
#alternative
#df = df.pivot('ID','Month')
df.columns = ['{0[1]}_{0[0]}'.format(x) for x in df.columns]
#alternative
#df.columns = df.columns.map('{0[1]}_{0[0]}'.format)
print (df)
     1_Price  2_Price  3_Price  1_Sale  2_Sale  3_Sale
ID                                                    
sk1      100      120      130       6       7       8
sk2       50       60       70       3       4       5

最后 reset_index + rename_axis:

df = df.reset_index().rename_axis(None, axis=1)
print (df)
    ID  1_Price  2_Price  3_Price  1_Sale  2_Sale  3_Sale
0  sk1      100      120      130       6       7       8
1  sk2       50       60       70       3       4       5