Reshape MultiIndex dataframe to tabular format

后端 未结 3 457
臣服心动
臣服心动 2020-12-10 09:41

Given a sample MultiIndex:

idx = pd.MultiIndex.from_product([[0, 1, 2], [\'a\', \'b\', \'c\', \'d\']])    
df = pd.DataFrame({\'value\' : np.arange(12)}, ind         


        
3条回答
  •  温柔的废话
    2020-12-10 10:00

    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
    

提交回复
热议问题