Reshape MultiIndex dataframe to tabular format

风格不统一 提交于 2019-11-28 10:36:55

Using unstack and stack

In [5359]: dff = df['value'].unstack()

In [5360]: dff
Out[5360]:
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

In [5361]: dff.stack().to_frame('name')
Out[5361]:
     name
0 a     0
  b     1
  c     2
  d     3
1 a     4
  b     5
  c     6
  d     7
2 a     8
  b     9
  c    10
  d    11

By using get_level_values

pd.crosstab(df.index.get_level_values(0),df.index.get_level_values(1),values=df.value,aggfunc=np.sum)
Out[477]: 
col_0  a  b   c   d
row_0              
0      0  1   2   3
1      4  5   6   7
2      8  9  10  11

Another alternative, which you should think of when using stack/unstack (though unstack is clearly better in this case!) is pivot_table:

In [11]: df.pivot_table(values="value", index=df.index.get_level_values(0), columns=df.index.get_level_values(1))
Out[11]:
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!