【问题标题】:How to include a sort criteria into a pivot_table function?如何将排序标准包含到 pivot_table 函数中?
【发布时间】:2021-10-31 07:21:21
【问题描述】:

下面是我在 df 数据帧上使用 pivot_table 函数的代码。

df = pd.DataFrame({'State' : ['B','B','A','A','C', 'C'],
           'Age' : ['1 to 5', '6 to 10', '1 to 5', '6 to 10', '1 to 5', '6 to 10'],
           'Vaccinated' : [80, 20, 30, 60, 10, 15],
           'Population': [100, 100, 100, 100, 100, 100],
           'Percentage' : [0.80, 0.20, 0.30, 0.60, 0.10,0.15]})

df1 = pd.pivot_table(df,values=["Vaccinated", "Population","Percentage"],index=["State", "Age"], aggfunc=np.sum)

早期代码的结果:

                   Percentage  Population  Vaccinated
State Age                                        
A     1 to 5         0.30         100          30
      6 to 10        0.60         100          60
B     1 to 5         0.80         100          80
      6 to 10        0.20         100          20
C     1 to 5         0.10         100          10
      6 to 10        0.15         100          15

但是,我想对我的记录进行排序,使状态 B 位于顶部,然后是 A,然后是 C。 合理是因为 B 州 100% 接种了疫苗(60%+40%),A 州接种了 90%(60%+30%),C 州接种了 25%。尝试添加几次排序,我遇到了错误。

我可以咨询一下如何在 pivot_table 期间或之后添加排序条件,以便我可以实现以下结果吗?

               Percentage  Population  Vaccinated
State Age                                        
B     1 to 5         0.80         100          80
      6 to 10        0.20         100          20
A     1 to 5         0.30         100          30
      6 to 10        0.60         100          60
C     1 to 5         0.10         100          10
      6 to 10        0.15         100          15

【问题讨论】:

    标签: python pandas pivot-table


    【解决方案1】:

    我们可以使用groupby sum 得到每个State 的总Vaccinated,然后sort_values 确定状态应该处于的顺序,然后我们可以在State 级别上使用reindex 重新排序基于组总数:

    df1 = df1.reindex(
        index=df1.groupby(level='State')['Vaccinated'].sum()
            .sort_values(ascending=False).index,
        level='State'
    )
    

    df:

                   Percentage  Population  Vaccinated
    State Age                                        
    B     1 to 5         0.80         100          80
          6 to 10        0.20         100          20
    A     1 to 5         0.30         100          30
          6 to 10        0.60         100          60
    C     1 to 5         0.10         100          10
          6 to 10        0.15         100          15
    

    【讨论】:

    • 感谢亨利的解释。详细的解释使我能够以小步骤理解和遵循代码。我注意到第一个,您的共享不使用 pivot_table 进行排序。我认为这是 pivot_table 功能的限制?
    • 数据透视表中的排序仅限于一列。透视表直到已经透视表之后才知道州级总计,这就是为什么我们需要在之后重新索引透视表。
    【解决方案2】:

    一种方法是使用 group sum 制作帮助列,按它对 df 进行排序,然后将其删除:

    df1 = df1.assign(Sum=df1.groupby(level=0).Vaccinated.transform('sum')).\
        sort_values(by='Sum', ascending=False).drop(columns=['Sum'])
    print(df1)
    

    打印:

                   Percentage  Population  Vaccinated
    State Age                                        
    B     1 to 5         0.80         100          80
          6 to 10        0.20         100          20
    A     1 to 5         0.30         100          30
          6 to 10        0.60         100          60
    C     1 to 5         0.10         100          10
          6 to 10        0.15         100          15
    

    【讨论】:

    • 谢谢。代码效果很好。
    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 2018-08-01
    • 2017-11-13
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多