如何将数据帧列转换为pandas中的行

时间:2017-06-21 14:23:09

标签: python pandas

我有以下数据框,并希望将第3列的列转换成行。请帮忙。

objectName.methodname = function_name;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }

  // OR THIS WORKS TOO

  myOtherMethod(params) {
    // ...do something else
  }
};

1 个答案:

答案 0 :(得分:5)

使用melt

df.melt(id_vars=['country','year','perc'])

旧版熊猫:

pd.melt(df, id_vars=['country','year','perc'])

输出:

  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

选项#2

df.set_index(['country','year','perc']).stack().reset_index()

输出:

  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