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

如何合并两个DataFrame并覆盖df1的xchRts列单元格值?

解决方法

方法1:Merge后合并列

先执行你原来的merge操作,再把df2的xchRts_y值填充到目标列,未匹配到的地方保留df1原有的xchRts_x值,最后清理多余列:

merged_df = pd.merge(df1, df2, how="left", on=['date', 'baseCcy', 'ccy'])
merged_df['xchRts'] = merged_df['xchRts_y'].fillna(merged_df['xchRts_x'])
# 删除不需要的拆分列
merged_df = merged_df.drop(columns=['xchRts_x', 'xchRts_y'])

最终的merged_df会保留df1的所有列,且匹配到的xchRts值已被df2覆盖。

方法2:用combine_first(更简洁)

先将两个DataFrame按匹配字段设为索引,通过combine_first让df2的xchRts覆盖df1对应位置的值,最后恢复原索引结构:

# 按匹配列设置索引
df1_indexed = df1.set_index(['date', 'baseCcy', 'ccy'])
df2_indexed = df2.set_index(['date', 'baseCcy', 'ccy'])

# 用df2的值覆盖df1,未匹配项保留df1原值
df1_indexed['xchRts'] = df2_indexed['xchRts'].combine_first(df1_indexed['xchRts'])

# 恢复原索引列
df_updated = df1_indexed.reset_index()

方法3:用update(直接修改原DataFrame)

update会直接用df2的非空值覆盖df1对应位置的数据,同样需要先对齐索引:

# 先复制原df1避免直接修改源数据
df_updated = df1.copy()
# 设置索引对齐
df_updated.set_index(['date', 'baseCcy', 'ccy'], inplace=True)
df2.set_index(['date', 'baseCcy', 'ccy'], inplace=True)

# 执行更新
df_updated.update(df2['xchRts'])

# 恢复原索引列
df_updated.reset_index(inplace=True)

内容的提问来源于stack exchange,提问作者Alex R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:52:42