如何将数据框列转换为熊猫中的行

Pli*_*nus 1 python pandas

我在下面的数据帧中,想将第3列后的列转置为行。请帮忙。

df:
country year    perc    data1   data2   data3
IN      2015    hjk     75      81      96
US      2015    KTM     100     289     632

Results:                
country year    perc    TransposedColumn    Value   
IN      2015    hjk     data1               75  
IN      2015    hjk     data2               81  
IN      2015    hjk     data3               96  
US      2015    KTM     data1               100 
US      2015    KTM     data2               289 
US      2015    KTM     data3               632 
Run Code Online (Sandbox Code Playgroud)

Sco*_*ton 6

用途melt:

df.melt(id_vars=['country','year','perc'])
Run Code Online (Sandbox Code Playgroud)

较旧版本的Pandas:

pd.melt(df, id_vars=['country','year','perc'])
Run Code Online (Sandbox Code Playgroud)

输出:

  country  year perc variable  value
0      IN  2015  hjk    data1     75
1      US  2015  KTM    data1    100
2      IN  2015  hjk    data2     81
3      US  2015  KTM    data2    289
4      IN  2015  hjk    data3     96
5      US  2015  KTM    data3    632
Run Code Online (Sandbox Code Playgroud)

选项#2

df.set_index(['country','year','perc']).stack().reset_index()
Run Code Online (Sandbox Code Playgroud)

输出:

  country  year perc level_3    0
0      IN  2015  hjk   data1   75
1      IN  2015  hjk   data2   81
2      IN  2015  hjk   data3   96
3      US  2015  KTM   data1  100
4      US  2015  KTM   data2  289
5      US  2015  KTM   data3  632
Run Code Online (Sandbox Code Playgroud)