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

如何通过name匹配用df2覆盖df1的favorite animal列值?

用df2替换df1同名行的指定列值

这里提供几种Pandas的实现方式,都能满足你的需求:

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

update()会直接在df1上更新匹配行的指定列值,操作高效且直观:

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Jack', 'Becca', 'Christie'],
    'favorite animal': ['cat', 'shark', 'dog', 'sheep', 'dinosaur']
})

df2 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Christie'],
    'favorite animal': ['dog', 'fish', 'monkey']
})

# 将name设为索引,确保匹配键一致
df1.set_index('name', inplace=True)
df2.set_index('name', inplace=True)

# 执行更新:用df2的值覆盖df1中同名行的对应列
df1.update(df2)

# 重置索引恢复原结构
df1.reset_index(inplace=True)

print(df1)

执行后df1会直接变成你想要的结果,原数据中不匹配的行保持不变。

方法2:使用combine_first()生成新DataFrame

如果你不想修改原df1,这个方法会返回一个新的结果集,同时保留原df1的行顺序:

import pandas as pd

df1 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Jack', 'Becca', 'Christie'],
    'favorite animal': ['cat', 'shark', 'dog', 'sheep', 'dinosaur']
})

df2 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Christie'],
    'favorite animal': ['dog', 'fish', 'monkey']
})

# 基于name索引合并,用df2的值优先填充
combined = df2.set_index('name').combine_first(df1.set_index('name')).reset_index()

# 恢复原df1的行顺序
result = combined.loc[combined['name'].isin(df1['name'])].reindex(df1['name'])

print(result)

方法3:字典映射替换

先把df2转换成键值对字典,再用map+fillna完成替换,适合场景简单的情况:

import pandas as pd

df1 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Jack', 'Becca', 'Christie'],
    'favorite animal': ['cat', 'shark', 'dog', 'sheep', 'dinosaur']
})

df2 = pd.DataFrame({
    'name': ['Mary', 'Benny', 'Christie'],
    'favorite animal': ['dog', 'fish', 'monkey']
})

# 构造{name: favorite animal}的替换字典
replace_map = df2.set_index('name')['favorite animal'].to_dict()

# 替换匹配项,未匹配的保留原数值
df1['favorite animal'] = df1['name'].map(replace_map).fillna(df1['favorite animal'])

print(df1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:15:43