【问题标题】:How to calculate groupwise proportion (within group propotion) for categorical columns using Python?如何使用 Python 计算分类列的分组比例(在组比例内)?
【发布时间】:2021-11-04 09:39:52
【问题描述】:

我找到了一个行之有效的单行解决方案。

这里的目标是估计研究中的位置性别比例。

# Data Frame
df = pd.DataFrame({"location": {0: "site 1", 1: "site 1", 2: "site 2", 3: "site 2", 4: "site 1"},
                   "gender": {0: "male", 1: "female", 2: "male", 3: "female", 4: "female"}})

print(df)

使用以下步骤产生结果

步骤 1. 应用 groupby

步骤 2. 使用 value_count

步骤 3. 使用 unstack

第 4 步。乘以 100 并将所有内容放入一个圆形函数中。

round(df.groupby(['location'])['gender'].value_counts(normalize = True).unstack()*100, 2)

还有其他解决方案吗?如果有人有其他解决方案/代码,请在此处分享。

【问题讨论】:

标签: python pandas pandas-groupby proportions


【解决方案1】:

这是一个很好的解决方案。

也许您可以将round(..., 2) 替换为.round(2) 并将NaN 填充为0。

>>> df.groupby('location')['gender'] \
      .value_counts(normalize=True) \
      .unstack() \
      .mul(100) \
      .round(2) \
      .fillna(0)

# Output
gender    female   male
location
site 1     66.67  33.33
site 2     50.00  50.00

您可以使用pd.crosstab 来代替groupby

>>> pd.crosstab(df['location'], df['gender']) \
      .apply(lambda x: round(x / x.sum() * 100, 2), axis=1)

# Output
gender    female   male
location
site 1     66.67  33.33
site 2     50.00  50.00

【讨论】:

    【解决方案2】:

    我有另一个解决方案,但这在 python 中使用了 R 的 dplyr 样式代码。为了实现这一点,我使用了 python 的 dfply 库。

    # Import libraries
    from dfply import *
    import pandas as pd
    
    # Data Frame
    df = pd.DataFrame({"location": {0: "site 1", 1: "site 1", 2: "site 2", 3: "site 2", 4: "site 1"},
                   "gender": {0: "male", 1: "female", 2: "male", 3: "female", 4: "female"}})
    
    
    # dfply code
    
    (
    df >>
    select(X.location, X.gender) >>
    group_by(X.location, X.gender) >>
    summarize(Count = n(X.gender)) >>
        group_by(X.location) >>
        mutate(Proportion = (X.Count/(X.Count).sum()).mul(100))
    ).round(2)
    

    这是结果

    【讨论】:

    • 我不明白您为什么喜欢更复杂的解决方案?这和你期望的输出不一样???
    • 实际上,我一直在寻找替代解决方案,而不仅仅是优化的解决方案。基本上,想知道在 Python 中实现相同输出的不同方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多