我有一个这样的数据框:
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转置,但它没有给出所需的结果。
答案 0 :(得分:0)
将set_index
与unstack
或pivot
一起使用,然后在MultiIndex
的列中展平list comprehension
:
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