【问题标题】:Pivoting (or reshaping) table in pandas into hierarchical columns将 pandas 中的表透视(或重塑)为分层列
【发布时间】:2019-01-22 15:21:16
【问题描述】:

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

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

【问题讨论】:

  • 这个你需要使用pd.pivot_tablepd.pivot_table(df2, index='city', columns=['year','type'], values='log_ratio')
  • How to pivot a dataframe 的可能重复项。请参阅该链接的问题 7。

标签: pandas pivot data-manipulation hierarchical


【解决方案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

【讨论】:

    猜你喜欢
    • 2023-02-13
    • 2018-01-05
    • 1970-01-01
    • 2021-10-14
    • 2015-08-21
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多