【问题标题】:pandas groupby to calculate percentage of groupby columnspandas groupby 计算 groupby 列的百分比
【发布时间】:2022-01-12 19:40:10
【问题描述】:

我想计算 rate_death 百分比如下 - (new_deaths / population) * 100 按位置分组并求和 new_deaths。

示例:对于阿富汗,rate_death 必须计算为 ((1+4+10) / 38928341) * 100 而对于阿尔巴尼亚,它必须计算为 ((0+0+1) / 2877800) * 100

以下是我尝试过但不起作用的数据和方法-

df_data
地点 日期 new_cases new_deaths 人口 0 阿富汗 2020 年 4 月 25 日 70 1 38928341 1 阿富汗 2020 年 4 月 26 日 112 4 38928341 2 阿富汗 2020 年 4 月 27 日 68 10 38928341 3 阿尔巴尼亚 2020 年 4 月 25 日 15 0 2877800 4 阿尔巴尼亚 2020 年 4 月 26 日 34 0 2877800 5 阿尔巴尼亚 2020 年 4 月 27 日 14 1 2877800 数据列(共5列): # 列非空计数 Dtype --- ------ -------------- ----- 0 位置 6 非空对象 1 个日期 6 个非空对象 2 new_cases 6 非空 int64 3 new_deaths 6 个非空 int64 4 人口 6 非空 int64

方法一:

df_res = df_data[['location','new_deaths','population']].groupby(['location']).sum()
位置 new_deaths 人口 阿富汗 15 116785023 阿尔巴尼亚 1 8633400
df_res['rate_death'] = (df_res['new_deaths'] / df_res['population'] * 100.0)
位置 new_deaths 人口 rate_death 阿富汗 15 116785023 0.000 阿尔巴尼亚 1 8633400 0.000

我知道由于上面的 groupby 使用“sum”操作,人口总计两次,但我仍然想知道为什么 rate_death 没有按预期计算百分比,而是显示为 0.000

方法 2:(已尝试如本文所述 - Pandas percentage of total with groupby

location_population = df_data.groupby(['location', 'population']).agg({'new_deaths': 'sum'})
location = df_data.groupby(['location']).agg({'population': 'mean'})
location_population.div(location, level='location') * 100
地点人口新死亡人口 阿富汗 38928341 NaN NaN 阿尔巴尼亚 2877800 NaN NaN

但它以 NaN 的形式出现。

如果这些方法有任何问题或如何解决,请提供帮助。谢谢!

【问题讨论】:

    标签: python pandas pandas-groupby sklearn-pandas


    【解决方案1】:

    你可以做-

    df = df.groupby(['location']).agg({'new_deaths': sum, 'population': max})
    df['rate_death'] = df['new_deaths'] / df['population'] * 100
    

    结果

                 new_deaths  population  rate_death
    location
    Afghanistan          15    38928341    0.000039
    Albania               1     2877800    0.000035
    

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 2019-01-26
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多