使用pandas groupby或pivot按指定分类列对两类别字段聚合求和与计数
pandas多字段分类聚合实现方案
前置准备:构建测试数据集
首先将样例数据加载为pandas的DataFrame,原始字段翻译如下:
- orgainzation_name → 公司名称
- structure → 岗位类型
- skills → 技能要求
import pandas as pd # 导入样例数据 raw_data = [ ["capgemini", "team_lead", "python"], ["capgemini", "manager", "pmp_certified"], ["capgemini", "analyst", "SQL"], ["wipro", "team_lead", "python"], ["wipro", "manager", "pmp_certified"], ["wipro", "analyst", "SQL"], ["infosys", "team_lead", "python"], ["infosys", "manager", "pmp_certifed"], ["infosys", "analyst", "SQL"], ["wipro", "manager", "pmp_certifed"], ["wipro", "analyst", "SQL"], ["wipro", "analyst", "SQL"], ["wipro", "analyst", "SQL"], ["wipro", "analyst", "SQL"], ["capgemini", "team_lead", "python"] ] df = pd.DataFrame(raw_data, columns=["公司名称", "岗位类型", "技能要求"])
实现方案1:groupby聚合
适合输出规整的一维统计结果,支持同时指定多个聚合规则:
# 按【公司名称】分组,同时统计岗位、技能的总记录数和去重后的数量 stat_result = df.groupby("公司名称", as_index=False).agg( 岗位总记录数=("岗位类型", "count"), 不同岗位种类数=("岗位类型", "nunique"), 技能总记录数=("技能要求", "count"), 不同技能种类数=("技能要求", "nunique") )
如果需要组合多维度分组,比如按公司+岗位二级分组统计技能数量,修改groupby的参数即可:
# 二级分组统计 stat_result_multi = df.groupby(["公司名称", "岗位类型"], as_index=False)["技能要求"].count()
实现方案2:pivot_table透视表聚合
适合输出交叉表形式的二维统计结果,直观展示多维度分布:
# 透视表:行是公司名称,列是岗位类型,值是对应岗位的记录数 pivot_post = pd.pivot_table( df, index="公司名称", columns="岗位类型", values="技能要求", aggfunc="count", fill_value=0 ) # 透视表:行是公司名称,列是技能要求,值是对应技能的记录数 pivot_skill = pd.pivot_table( df, index="公司名称", columns="技能要求", values="岗位类型", aggfunc="count", fill_value=0 )
参数说明:
aggfunc:聚合函数,计数传count,如果是对数值列求和传sum即可fill_value:将统计结果中的空值替换为0,避免后续计算报错
内容的提问来源于stack exchange,提问作者seek
相关产品推荐
相关产品推荐

