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

Pandas入门问题:合并同值行并汇总指定列结果不符合预期

Pandas合并重复行并指定列汇总的问题

我是一名Pandas初学者,现有DataFrame存在多行Sl.No、Catalogue No.、Catalogue Description等列值完全相同的记录,想要合并这些行,仅对Quantity和total quantity列进行求和汇总,其余列保持不变。

期望输出:合并相同值的行后,仅目标列是汇总后的数值,其他列与原行一致。

我尝试使用以下代码:

d.groupby(['Sl.No','Catalogue No.','Catalogue Description','Nature of component','Compartment Width','Compartment Height', 'UOM']).sum().reset_index()

但得到的输出不符合预期。


问题原因

groupby().sum()会对所有数值类型的列执行求和操作,而非仅针对你需要的Quantity和total quantity列。如果分组内其他数值列(比如尺寸列)原本值相同,求和后结果看似正常,但如果存在数据异常就会出错;另外如果某些文本列被误识别为数值类型,还会导致错误的拼接/求和。

解决方案

方法1:指定列的聚合规则

明确指定哪些列需要求和,哪些列保留分组内的第一个值(因为分组内这些列值一致):

# 定义聚合规则:求和列+保留原值的列
agg_rules = {
    'Quantity': 'sum',
    'total quantity': 'sum',
    'Sl.No': 'first',
    'Catalogue No.': 'first',
    'Catalogue Description': 'first',
    'Nature of component': 'first',
    'Compartment Width': 'first',
    'Compartment Height': 'first',
    'UOM': 'first'
}

# 执行分组聚合
result = d.groupby(
    ['Sl.No','Catalogue No.','Catalogue Description','Nature of component','Compartment Width','Compartment Height', 'UOM'],
    as_index=False
).agg(agg_rules)

如果列名较多,可用代码自动生成聚合规则,避免手动输入:

sum_cols = ['Quantity', 'total quantity']
# 自动获取其他需要保留原值的列
other_cols = [col for col in d.columns if col not in sum_cols]

# 构建聚合字典
agg_rules = {col: 'sum' for col in sum_cols}
agg_rules.update({col: 'first' for col in other_cols})

result = d.groupby(
    ['Sl.No','Catalogue No.','Catalogue Description','Nature of component','Compartment Width','Compartment Height', 'UOM'],
    as_index=False
).agg(agg_rules)

方法2:检查分组键的细微差异

如果上述方法仍未得到预期结果,大概率是分组键的列存在肉眼不可见的差异(比如前后空格、大小写不一致、换行符),先清洗这些列再分组:

# 清洗文本类型的分组键列:去除前后空格、统一大小写(按需调整)
text_group_cols = ['Catalogue No.','Catalogue Description','Nature of component','UOM']
for col in text_group_cols:
    d[col] = d[col].str.strip()  # 去除前后空格
    # d[col] = d[col].str.lower()  # 统一小写,不需要可注释

# 再执行方法1的聚合操作
sum_cols = ['Quantity', 'total quantity']
other_cols = [col for col in d.columns if col not in sum_cols]
agg_rules = {col: 'sum' for col in sum_cols}
agg_rules.update({col: 'first' for col in other_cols})

result = d.groupby(
    ['Sl.No','Catalogue No.','Catalogue Description','Nature of component','Compartment Width','Compartment Height', 'UOM'],
    as_index=False
).agg(agg_rules)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:48:15