如何在Pandas Series中手动合并指定分类?
手动合并Pandas Series中的指定分类
步骤1:构造示例Series(已有数据可跳过)
先还原你的数据集为Pandas Series:
import pandas as pd data = { 'HS-grad': 15784, 'Some-college': 10878, 'Bachelors': 8025, 'Masters': 2657, '11th': 1812, '10th': 1389, '7th-8th': 955, '9th': 756, '12th': 657, '5th-6th': 509, '1st-4th': 247 } s = pd.Series(data, name='number_of_appearances')
步骤2:自定义合并规则
创建映射字典,明确指定哪些分类要合并为新名称,其余分类可映射到自身保持不变:
# 定义合并规则:原分类 → 新分类名 merge_map = { '1st-4th': '(1st-4th, 5th-6th)', '5th-6th': '(1st-4th, 5th-6th)', 'HS-grad': 'HS-grad', 'Some-college': 'Some-college', 'Bachelors': 'Bachelors', 'Masters': 'Masters', '11th': '11th', '10th': '10th', '7th-8th': '7th-8th', '9th': '9th', '12th': '12th' }
步骤3:执行合并
通过map替换分类名,再分组求和得到结果:
merged_s = s.map(merge_map).groupby(level=0).sum()
最终结果
运行后得到的merged_s输出如下:
HS-grad 15784 Some-college 10878 Bachelors 8025 Masters 2657 11th 1812 10th 1389 7th-8th 955 9th 756 12th 657 (1st-4th, 5th-6th) 756 Name: number_of_appearances, dtype: int64
扩展:多组合并
如果需要合并更多分类组,只需修改merge_map即可。比如合并9th、10th、11th、12th为统一名称:
merge_map = { '1st-4th': '(1st-4th, 5th-6th)', '5th-6th': '(1st-4th, 5th-6th)', '9th': 'Lower Secondary/High School Dropout', '10th': 'Lower Secondary/High School Dropout', '11th': 'Lower Secondary/High School Dropout', '12th': 'Lower Secondary/High School Dropout', 'HS-grad': 'HS-grad', 'Some-college': 'Some-college', 'Bachelors': 'Bachelors', 'Masters': 'Masters', '7th-8th': '7th-8th' } merged_s = s.map(merge_map).groupby(level=0).sum()
这个方法完全由你自定义合并规则,和R语言forcats包的fct_collapse功能逻辑一致,满足手动指定合并分类的需求。
内容的提问来源于stack exchange,提问作者BoroBoro
相关产品推荐
相关产品推荐

