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

pandas基于主键列按条件用另一DataFrame替换原df对应数值

pandas按主键匹配取较大值更新表数据实现方案

实现逻辑

  • 以col1作为公共主键对齐两张表的行数据
  • 逐行对比两张表的col2值,仅当df2的col2值更大时才替换df1的对应值
  • 未匹配到主键的行直接保留df1的原始值

方法1:索引对齐实现(性能更高,适合大数据量)

import pandas as pd

# 输入示例数据
d1 = {'col1': ['a','b','c','d'], 'col2': [1,2,3,4]}
d2 = {'col1': ['a','b','c'], 'col2': [0,3,4]}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# 核心处理
df1_idx = df1.set_index('col1')
df2_idx = df2.set_index('col1')
df1_idx['col2'] = df2_idx['col2'].where(df2_idx['col2'] > df1_idx['col2'], df1_idx['col2'])
df1 = df1_idx.reset_index()

# 输出结果
print(df1)

方法2:merge合并实现(逻辑更直观,适合多字段更新场景)

import pandas as pd

# 输入示例数据
d1 = {'col1': ['a','b','c','d'], 'col2': [1,2,3,4]}
d2 = {'col1': ['a','b','c'], 'col2': [0,3,4]}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# 核心处理
df1 = df1.merge(df2, on='col1', how='left', suffixes=('', '_df2'))
df1['col2'] = df1[['col2', 'col2_df2']].max(axis=1)
df1 = df1.drop(columns='col2_df2')

# 输出结果
print(df1)

运行输出结果

col1  col2
0    a     1
1    b     3
2    c     4
3    d     4

完全符合预期输出要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:24:04