You need to enable JavaScript to run this app. Python合并两个DataFrame,用df2值覆盖df1中x、y列相同的行
优惠活动
大模型
产品
解决方案
定价
更多

Python合并两个DataFrame,用df2值覆盖df1中x、y列相同的行

问题定位

你的原有代码不符合需求的核心原因有两点:

  • 匹配成功的分支取值逻辑错误:np.where中_merge == 'both'时你取了population_x(即第一个DataFrame的population值),和“用第二个DataFrame值覆盖”的需求完全相反
  • 非匹配分支的逻辑错误:你使用了add求和操作,需求仅需要保留单侧存在行的population值,不需要相加

正确实现方案

方案1:基于merge逻辑修改(适配你原有写法)

假设第一个待合并DataFrame为df1,第二个用于覆盖的DataFrame为df2,代码如下:

import pandas as pd
import numpy as np

# 按x、y列外连接合并两个DataFrame
df_out = df1.merge(df2, on=['x', 'y'], how='outer', indicator=True)

# 匹配成功用第二个DataFrame的population,未匹配则保留单侧存在的值
df_out['population'] = np.where(
    df_out['_merge'] == 'both',
    df_out['population_y'],
    df_out['population_x'].fillna(df_out['population_y'])
).astype(int)

# 提取最终需要的列
df_result = df_out[['x', 'y', 'population']]

方案2:更简洁的update实现

利用pandas内置的索引匹配更新方法,无需手动判断合并状态:

# 把x、y设为索引,用于行匹配
df1_idx = df1.set_index(['x', 'y'])
df2_idx = df2.set_index(['x', 'y'])

# 用df2的值覆盖df1中匹配到的行
df1_idx.update(df2_idx)
# 拼接df2中独有的行,重置索引得到最终结果
df_result = pd.concat([df1_idx, df2_idx[~df2_idx.index.isin(df1_idx.index)]]).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:45:02