枢轴"堆积"有多个索引的数据?

时间:2013-05-26 20:02:18

标签: pandas

我有一些看似这样的“堆叠”或“记录格式”数据(来自数据库):

"recid","code","value","exam_num"  
"101703034","k_rat1","17/18","1"  
"200907062","e_mas1","AC YES","6"  
"203004134","k_rat1","5/18","5"  
"303505091","k_gtrdsc","Foo","1"  
"303505091","k_rat1","4/18","2"  

我想把它转到这样:

recid,exam_num,k_rat1,e_mas1,k_gtrdsc
101703034,1,"17/18",,
200907062,6,,"AC YES",
203004134,5,"5/18",,
303505091,1,,,Foo
303505091,2,"4.18",,

我可以使用这样的一个索引(recid):

my_df = read_csv("data.csv")
pivoted = my_df.pivot(index="recid",columns="code",values="value")

这给了我这个(注意缺少的exam_num专栏):

recid,e_mas1,k_gtrdsc,k_rat1
101703034,,,17/18
200907062,AC YES,,
203004134,,,5/18
303505091,,Foo,4/18

然而,当我尝试指定多个索引或大多数其他任何东西时,我会遇到各种错误。我读过这个:http://pandas.pydata.org/pandas-docs/stable/reshaping.html,但看不出办法完全按照我的意思去做。

非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

您可以设置多级索引,然后将unstack该索引中的级别设置回列:

pivoted = my_df.set_index(['recid', 'exam_num', 'code']).unstack('code')