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

合并两个DataFrame并按规则汇总列值的技术实现问询

解决方案

你的问题在于直接合并两个DataFrame后没有按客户名称汇总数值,导致同一客户的多条记录没有合并。以下是修改后的代码,能实现你想要的汇总效果:

步骤说明

  1. 分别对两个DataFrame按Customer_Name分组,汇总Jan和Feb的数值,同时保留每个客户对应的一个Customer_No(这里取首次出现的编号,你可以根据需求调整);
  2. 合并两个汇总后的结果,用outer join确保所有客户都被保留;
  3. 填充缺失值为0,并整理列顺序。

修改后的代码

import pandas as pd

df1 = pd.DataFrame({'Customer_Name': ['foo', 'bar', 'baz', 'foo'],
                    'Customer_No': ['01', '02', '03', '04'],
                    'Jan': [1, 2, 3, 4]})
df2 = pd.DataFrame({'Customer_Name': ['foo', 'bar', 'baz', 'foo','bad','bag'],
                    'Customer_No': ['01', '02', '03', '01','05','06'],
                    'Feb': [5, 6, 7, 8, 9, 10]})

# 汇总df1:按Customer_Name求和Jan,保留首个Customer_No
df1_agg = df1.groupby('Customer_Name', as_index=False).agg(
    Jan=('Jan', 'sum'),
    Customer_No=('Customer_No', 'first')
)

# 汇总df2:按Customer_Name求和Feb,保留首个Customer_No
df2_agg = df2.groupby('Customer_Name', as_index=False).agg(
    Feb=('Feb', 'sum'),
    Customer_No=('Customer_No', 'first')
)

# 合并两个汇总表,outer join确保所有客户都被包含
df4 = df1_agg.merge(df2_agg, on='Customer_Name', how='outer', suffixes=('_df1', '_df2'))

# 处理Customer_No:优先取df1中的编号,没有则用df2的
df4['Customer_No'] = df4['Customer_No_df1'].fillna(df4['Customer_No_df2'])

# 填充缺失的Jan/Feb为0,并转为整数
df4['Jan'] = df4['Jan'].fillna(0).astype(int)
df4['Feb'] = df4['Feb'].fillna(0).astype(int)

# 整理列顺序
df4 = df4[['Customer_Name', 'Customer_No', 'Jan', 'Feb']]

print(df4)

输出结果

Customer_Name Customer_No  Jan  Feb
0           foo          01    5   13
1           bar          02    2    6
2           baz          03    3    7
3           bad          05    0    9
4           bag          06    0   10

注:你给出的期望输出中bad和bag的Customer_No及Feb数值与原始数据不符,推测是笔误。上述代码基于你提供的原始df1和df2生成正确的汇总结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:35:41