pandas dataframe transforms with columns and specific rows

时间:2017-10-08 07:55:35

标签: python pandas

i am working with pandas with dataframe like bleow

area    date    m1  m2
IDC1    02/01/2017  400 80
IDC1    03/01/2017  400 70
IDC2    02/01/2017  410 204
IDC2    03/01/2017  400 214

i wnat to transform it to below, i have been seen the pd.melt,but still not working.

area    date    02/01/2017  03/01/2017
IDC1    m1       400         400
IDC1    m2        80          70
IDC2    m1       410         400
IDC2    m2       204         214

1 个答案:

答案 0 :(得分:1)

set_indexstackunstack一起使用:

df = (df.set_index(['area', 'date'])
       .stack()
       .unstack(1, fill_value=0)
       .rename_axis(('area','date'))
       .rename_axis(None, 1)
       .reset_index())
print (df)
   area date  02/01/2017  03/01/2017
0  IDC1   m1         400         400
1  IDC1   m2          80          70
2  IDC2   m1         410         400
3  IDC2   m2         204         214