我有一个如下所示的熊猫数据框
Descr id state 01/2012 02/2012 04/2012 05/2015 08/2018
aa 1 new 20 30 40 50 60
而且,我想将其更改为
DateRange Descr id state value
01/2012 aa 1 new 20
02/2012 aa 1 new 30
04/2012 aa 1 new 40
05/2015 aa 1 new 50
08/2018 aa 1 new 60
答案 0 :(得分:1)
df = df.melt(['Descr','id','state'], var_name='DateRange')
#change order of columns if necessary
df = df[['DateRange','Descr','id','state','value']]
print (df)
DateRange Descr id state value
0 01/2012 aa 1 new 20
1 02/2012 aa 1 new 30
2 04/2012 aa 1 new 40
3 05/2015 aa 1 new 50
4 08/2018 aa 1 new 60