【问题标题】:Customized normalization of pd.crosstab()pd.crosstab() 的自定义规范化
【发布时间】:2021-11-29 23:21:32
【问题描述】:

我正在使用 pandas 数据框并使用以下交叉表公式将结果制成表格:

ct = pd.crosstab(index=[df['Gender'], df['Education'],df['MaritalStatus']],
                                 columns=df['month'], normalize='columns').round(2)

交叉表的输出:

我不希望按整列计算百分比。相反,例如,对于第一行,我想要的输出是计算 Level0 和 Single / Number of Females who is Level 0 的女性百分比(以黄色突出显示)。

有什么方法可以做到这一点?

【问题讨论】:

    标签: python pandas dataframe crosstab


    【解决方案1】:

    使用GroupBy.transform 并划分原始输出(也删除了normalize='columns'):

    ct = pd.crosstab(index=[df['Gender'], df['Education'],df['MaritalStatus']],
                            columns=df['month'])
    
    #normalize by levels Gender and Education
    ct = ct.div(ct.groupby(level=['Gender','Education']).transform('sum')).round(2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2014-05-25
      • 2017-05-02
      • 2011-03-06
      • 2016-10-05
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多