将熊猫中的表透视(或整形)为层次列

时间:2018-08-15 17:53:10

标签: pandas pivot data-manipulation hierarchical

我有一个df,例如...

     log_ratio   city   type   year
0   2.892095   Detroit  Pos_A  2016
1   2.176814   Detroit  Pos_B  2016
2   3.218273   Detroit  Pos_A  2017
3   2.922206   Detroit  Pos_B  2017
4   2.776701  Columbus  Pos_A  2016
5   2.615424  Columbus  Pos_B  2016
6   2.781899  Columbus  Pos_A  2017
7   2.499343  Columbus  Pos_B  2017
...

我想重塑此表,以使city是索引,而yeartype成为一个层次列,而log_ratio是值,例如...

 mr             2016                2017

           Pos_A    Pos_B      Pos_A   Pos_B 

Detroit  2.892095 2.176814   3.218273 2.922206
Columbus 2.776701 2.615424   2.781899 2.499343
...

当我运行命令时...

df3 = df2.pivot(index='mr',columns=['year','type'],values='log_ratio')

我得到一个错误...

 'Cannot find level year'.

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

我认为您只需要pivot_table而不是pivot

df.pivot_table(index='city', columns=['year','type'], values='log_ratio')
year          2016                2017          
type         Pos_A     Pos_B     Pos_A     Pos_B
city                                            
Columbus  2.776701  2.615424  2.781899  2.499343
Detroit   2.892095  2.176814  3.218273  2.922206

有关更多详细信息,请查看以下令人敬畏的规范答案:How to pivot a dataframe