将 pandas 中的 table 旋转(或重塑)到分层列中

Pivoting (or reshaping) table in pandas into hierarchical columns

我有一个 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
...

我想重塑此 table,使 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'.

如有任何帮助,我们将不胜感激。谢谢!

我想你只需要 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

有关更多详细信息,请查看这个很棒的规范答案: