转置DataFrame

时间:2017-10-16 13:03:49

标签: python pandas dataframe transpose

我有以下DataFrame -

df_altered
Out[748]: 
   ID_Patient Name_Patient month  year    U    A    Z
0       11132          Jim   Jan  2012  5.0  2.0  NaN
1       11132          Jim   Feb  2012  NaN  4.0  6.0
2        2755         Jack   Apr  2012  1.0  3.0  1.0
3        9753          Sue   Jan  2012  8.0  5.0  NaN
4        9753          Sue   Feb  2012  NaN  NaN  1.0

如何将其转换为:

WITH TIES

我试图使用以下方法解决它,但无济于事。

  

.set_index(....)。拆散()

有关如何使用上述功能实现这一目标的任何建议? 感谢你的期待

2 个答案:

答案 0 :(得分:2)

确切地说,你是对的 - 需要set_indexunstack

df1 = (df.set_index(['ID_Patient', 'Name_Patient','month','year','visits'])['var']
         .unstack()
         .reset_index()
         .rename_axis(None, 1))
print (df1)
   ID_Patient Name_Patient month  year    A    U    Z
0        2755         Jack   Apr  2012  3.0  1.0  1.0
1        9753          Sue   Feb  2012  NaN  NaN  1.0
2        9753          Sue   Jan  2012  5.0  8.0  NaN
3       11132          Jim   Feb  2012  4.0  NaN  6.0
4       11132          Jim   Jan  2012  2.0  5.0  NaN

答案 1 :(得分:2)

您可以使用mlock之类的

pivot_table