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

如何对两个DataFrame中相同id的total值求平均并生成新DataFrame

问题描述

我有如下两个DataFrame:

import pandas as pd

df1 = pd.DataFrame({
    'id': {4: 1548638, 6: 1953603, 7: 1956216, 8: 1962245, 9: 1981386, 10: 1981773, 11: 2004787, 13: 2017418, 14: 2020989, 15: 2045043},
    'total': {4: 17, 6: 38, 7: 59, 8: 40, 9: 40, 10: 40, 11: 80, 13: 44, 14: 51, 15: 46}
})

df2 = pd.DataFrame({
    'id': {4: 1548638, 6: 1953603, 7: 1956216, 8: 1962245, 9: 1981386, 10: 1981773, 11: 2004787, 13: 2017418, 14: 2020989, 15: 2045043},
    'total': {4: 17, 6: 38, 7: 59, 8: 40, 9: 40, 10: 40, 11: 80, 13: 44, 14: 51, 15: 46}
})

我希望对两个DataFrame中均存在的每个id,计算其total值的平均值,并将结果存入新的DataFrame中。

尝试了以下代码但无法正常运行:

pd.merge(df1, df2, on="id")
merged_df[['total']].mean(axis=1)
解决方案

你的问题出在merge操作后,两个原本名为total的列会被自动重命名为total_x和total_y,此时直接调用merged_df[['total']]会因为找不到对应列而报错。下面提供几种可行的实现方式:

方法一:合并后计算均值

先完成合并,针对重命名后的列计算均值,再整理成目标DataFrame:

# 合并两个DataFrame,指定关联键为id
merged_df = pd.merge(df1, df2, on="id")
# 计算每行total_x和total_y的均值,生成新列mean_total
merged_df['mean_total'] = merged_df[['total_x', 'total_y']].mean(axis=1)
# 提取需要的id和均值列,得到最终结果
result_df = merged_df[['id', 'mean_total']]

方法二:直接对齐计算(简洁高效)

利用pandas的自动对齐特性,直接对两个DataFrame的total列做算术运算,同时保留id列:

# 直接计算均值,pandas会自动按索引对齐
result_df = pd.DataFrame({
    'id': df1['id'],
    'mean_total': (df1['total'] + df2['total']) / 2
})

# 若担心两个DataFrame的id不完全重叠,可先筛选出共同存在的id
common_ids = df1[df1['id'].isin(df2['id'])]['id']
result_df = pd.DataFrame({
    'id': common_ids,
    'mean_total': (df1.loc[common_ids.index, 'total'] + df2.loc[common_ids.index, 'total']) / 2
})

方法三:拼接后分组计算(通用扩展性强)

将两个DataFrame纵向拼接,再按id分组求均值,这种方法支持后续添加更多同结构的DataFrame:

# 纵向拼接两个DataFrame
combined_df = pd.concat([df1, df2])
# 按id分组,计算total列的均值,最后重置索引转为常规DataFrame
result_df = combined_df.groupby('id')['total'].mean().reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:55:17