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

如何高效合并多类别列后用groupby和value_counts统计收入占比?

需求说明

我的DataFrame包含一列marital-status,其唯一值为:'Married-civ-spouse'、'Married-spouse-absent'、'Married-AF-spouse'、'Divorced'、'Widowed'、'Separated'。需通过groupby和value_counts统计各收入类别的占比,得到合并分组后的结果:

marital-status  salary
Bachelor        <=50K     0.935546
                >50K      0.064454
Married         <=50K     0.563080
                >50K      0.436920

而非当前的细分统计结果:

marital-status         salary
Divorced               <=50K     0.895791
                       >50K      0.104209
Married-AF-spouse      <=50K     0.565217
                       >50K      0.434783
Married-civ-spouse     <=50K     0.553152
                       >50K      0.446848
Married-spouse-absent  <=50K     0.918660
                       >50K      0.081340
Never-married          <=50K     0.954039
                       >50K      0.045961
Separated              <=50K     0.935610
                       >50K      0.064390
Widowed                <=50K     0.914401
                       >50K      0.085591

分组规则:所有以'Married'开头的类别合并为'Married',其余类别合并为'Bachelor'。之前尝试过replace函数,现寻求更高效的替代方案。

高效解决方案

以下两种方法均为向量化操作,性能优于replace,尤其适合大数据量场景:

方法1:Pandas字符串向量化操作

直接基于原列生成合并分组标签,再执行分组统计:

import pandas as pd

# 生成合并分组列
df['marital_group'] = df['marital-status'].str.startswith('Married').map({True: 'Married', False: 'Bachelor'})

# 分组计算收入占比
result = df.groupby('marital_group')['salary'].value_counts(normalize=True).round(6)

# 调整索引名称以匹配目标格式
result.index.names = ['marital-status', 'salary']
print(result)

方法2:Numpy向量化判断

利用Numpy的底层C实现,速度比Pandas apply更快:

import pandas as pd
import numpy as np

# 生成合并分组列
df['marital_group'] = np.where(df['marital-status'].str.startswith('Married'), 'Married', 'Bachelor')

# 分组计算收入占比
result = df.groupby('marital_group')['salary'].value_counts(normalize=True).round(6)
result.index.names = ['marital-status', 'salary']
print(result)

关键说明

  • value_counts(normalize=True)直接返回分组内的占比,无需手动计算比例;
  • str.startswith是Pandas内置的向量化字符串方法,避免了循环操作的性能损耗;
  • Numpy的where函数执行效率更高,数据量越大,性能优势越显著。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:37:10