如何使用pandas对大小写不同但名称相同的列进行分组求和合并?
实现pandas大小写差异重名列合并方案
核心逻辑
- 以列名的全小写为分组依据,将仅大小写不同的列归为同一组
- 单元素分组直接保留原列名与数值,满足无匹配列的全大写列(如示例中的
JFK)保留需求 - 多元素分组优先选取非全大写格式的列名作为最终列名,对同组所有列的值求和合并
完整实现代码
import pandas as pd from collections import defaultdict # 构造示例DataFrame df = pd.DataFrame({ 'Carl': [1], 'CARL': [3], 'Carl Smith': [7], 'David': [4], 'John': [2], 'JFK': [9] }) # 按列名小写形式分组 col_groups = defaultdict(list) for col in df.columns: col_groups[col.lower()].append(col) # 处理分组生成结果 result = pd.DataFrame() for lower_name, cols in col_groups.items(): if len(cols) == 1: result[cols[0]] = df[cols[0]] else: # 选取非全大写的列作为最终列名 final_col = next(c for c in cols if not c.isupper()) result[final_col] = df[cols].sum(axis=1) print(result)
输出验证
运行上述代码后输出结果与预期完全一致:
Carl Carl Smith David John JFK 0 4 7 4 2 9
内容的提问来源于stack exchange,提问作者Jacob Myer
相关产品推荐
相关产品推荐

