如何使用Python将列值转换为行标题?

时间:2019-03-12 09:46:16

标签: python pandas dataframe

我需要将列值转换为python中的标头。

Intent i1 = new Intent();
i1.setData(Uri.parse("baidumap://map/direction?mode=driving&destination=上上&origin=西二旗&src=push&viaPoints={viaPoints:[{name:Beijing West Railway Station, lat:39.902463,lng:116.327737}]}"));
startActivity(i1);

enter image description here

我想要一张像这样的桌子

enter image description here

当我尝试以下代码时

    testdf = {'Student_id':['10001','10001','10001','20001','20001','30001','30001','30001'],
          'Subject':['S1','S2','S3','S1','S2','S1','S2','S3'],
          'Mark':['80','60','70','50','70','90','80','40']
         }
testdf = pd.DataFrame(data=testdf)
testdf

我将得到以下信息:

enter image description here

1 个答案:

答案 0 :(得分:3)

将参数values添加到DataFrame.pivot,并在必要时清除数据-用DataFrame.rename_axis删除列名,用DataFrame.reset_index删除index中的列:

df = (testdf.pivot(index="Student_id",columns="Subject", values='Mark')
            .rename_axis(None, axis=1)
            .reset_index())
print (df)
  Student_id  S1  S2   S3
0      10001  80  60   70
1      20001  50  70  NaN
2      30001  90  80   40