You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中替换for循环实现占比统计?

问题描述

我有一个处理不同区域和国家预期寿命文章数据的DataFrame,需要统计:

  • 各区域文章占总文章的比例
  • 各区域内男性、女性、双性相关文章的占比

目前用带for循环的calc_proportion函数实现,但想替换掉for循环,生成目标结果DataFrame。原函数代码如下:

def calc_proportion(df):
    proportions = pd.DataFrame(columns=['Region', 'Proportion_of_all_articles', 'Proportion_male_articles', 'Proportion_female_articles', 'Proportion_bs_articles'])
    Regions = df.Region.unique()
    for region in Regions:
        a = f"{df.loc[df['Region'] == region].shape[0] / df.shape[0] : .0%}"
        b = f"{df.loc[(df['Region'] == region) & (df['Sex'] == 'Male')].shape[0] / df.loc[df['Region'] == region].shape[0] : .0%}"
        c = f"{df.loc[(df['Region'] == region) & (df['Sex'] == 'Female')].shape[0] / df.loc[df['Region'] == region].shape[0] : .0%}"
        d = f"{df.loc[(df['Region'] == region) & (df['Sex'] == 'Both sexes')].shape[0] / df.loc[df['Region'] == region].shape[0] : .0%}"
        proportions.loc[len(proportions)] = [region, a, b, c, d]
    return proportions

calc_proportion(df)
无for循环实现方案

利用Pandas的分组、透视表和向量运算功能,可高效替代for循环,代码如下:

import pandas as pd

def calc_proportion(df):
    # 统计各区域文章总数及占总文章的比例
    region_summary = df.groupby('Region').size().reset_index(name='region_total')
    total_all = df.shape[0]
    region_summary['Proportion_of_all_articles'] = (region_summary['region_total'] / total_all).map("{:.0%}".format)
    
    # 统计各区域内不同性别的文章占比
    sex_counts = df.pivot_table(index='Region', columns='Sex', aggfunc='size', fill_value=0)
    sex_proportions = (sex_counts.div(sex_counts.sum(axis=1), axis=0)).map("{:.0%}".format)
    
    # 合并结果并调整列名、顺序
    final_result = pd.merge(region_summary, sex_proportions, on='Region')
    final_result = final_result.rename(columns={
        'Male': 'Proportion_male_articles',
        'Female': 'Proportion_female_articles',
        'Both sexes': 'Proportion_bs_articles'
    })
    
    # 保留目标列并排序
    final_result = final_result[[
        'Region', 
        'Proportion_of_all_articles', 
        'Proportion_male_articles', 
        'Proportion_female_articles', 
        'Proportion_bs_articles'
    ]]
    return final_result

代码说明

  • 区域占比计算:通过groupby('Region').size()快速统计各区域文章数,再除以总文章数得到占比,用map格式化百分比。
  • 性别占比计算:用pivot_table按区域-性别分组计数,再通过div按行计算各性别占区域总数的比例,同样格式化百分比。
  • 结果合并:将区域占比和性别占比的结果合并,调整列名和顺序,完全匹配原函数的输出格式。

内容的提问来源于stack exchange,提问作者Anna_Kr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:20:05