【问题标题】:Pivoting a table with duplicate index透视具有重复索引的表
【发布时间】:2021-05-14 19:43:57
【问题描述】:

我想旋转这个表格:

    Year    County  Sex     rate
0   2006    Alameda Male    45.80
1   2006    Alameda Female  54.20
2   2006    Alpine  Male    52.81
3   2006    Alpine  Female  47.19
4   2006    Amador  Male    49.97
5   2006    Amador  female  50.30

我想要的输出是:

Year    County  Male  Female
2006    Alameda 45.80 54.20
2006    Alameda 52.81 47.19
2006    Alpine  49.97 50.30

我试过这样做:

sex_rate=g.pivot(index="County",columns='Year',values='rate')

但我不断收到此错误:

ValueError: Index contains duplicate entries, cannot reshape

请帮忙。我是python新手

【问题讨论】:

    标签: python-3.x pandas pivot reshape


    【解决方案1】:

    我想你想要index=['Year', 'County'],而不仅仅是index='County'。由于您将两列传递给index,因此您可能希望使用pivot_table 而不是pivot

    df.pivot_table(index=['Year','County'], 
                   columns='Sex', values='rate'
                  ).reset_index()
    

    输出:

    Sex  Year   County  Female   Male
    0    2006  Alameda   54.20  45.80
    1    2006   Alpine   47.19  52.81
    2    2006   Amador   50.30  49.97
    

    【讨论】:

    • 太棒了...谢谢!
    猜你喜欢
    • 2015-10-04
    • 2018-06-20
    • 2018-06-26
    • 1970-01-01
    • 2020-08-30
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多