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

Python3下匹配DataFrame行,用df2的class值更新df1对应行

嘿,我来帮你解决这个Pandas数据匹配替换的问题,这里有两种实用的方法,都能完美实现你的需求:

方法1:Merge 结合 Fillna

这种方法通过左连接两个DataFrame,然后用df2的class值填充df1中匹配行的对应值,逻辑清晰易懂:

import pandas as pd

# 构造示例数据(和你提供的结构一致)
df1 = pd.DataFrame({
    'num1': [1, 1, 1, 2],
    'num2': [2, 2, 2, 2],
    'num3': [3, 4, 5, 4],
    'class': [0, 0, 0, 0]
})

df2 = pd.DataFrame({
    'num1': [1, 1],
    'num2': [2, 2],
    'num3': [3, 4],
    'class': [1, 1]
})

# 左连接df1和df2的匹配列+class列,添加后缀区分原列和新列
merged_df = df1.merge(
    df2[['num1', 'num2', 'num3', 'class']],
    on=['num1', 'num2', 'num3'],
    how='left',
    suffixes=('_original', '_new')
)

# 用df2的class值替换匹配行,未匹配的保留原class值
merged_df['class'] = merged_df['class_new'].fillna(merged_df['class_original'])

# 整理得到最终结果,确保class是整数类型
df12 = merged_df[['num1', 'num2', 'num3', 'class']].astype({'class': int})
print(df12)

方法2:Set Index 结合 Update

这种方法更简洁高效,利用索引匹配直接更新值,适合数据量较大的场景:

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({
    'num1': [1, 1, 1, 2],
    'num2': [2, 2, 2, 2],
    'num3': [3, 4, 5, 4],
    'class': [0, 0, 0, 0]
})

df2 = pd.DataFrame({
    'num1': [1, 1],
    'num2': [2, 2],
    'num3': [3, 4],
    'class': [1, 1]
})

# 先复制df1避免修改原数据(如果不需要保留原df1可以跳过这步)
df1_copy = df1.copy()

# 将两个DataFrame的匹配列设置为索引
df1_copy.set_index(['num1', 'num2', 'num3'], inplace=True)
df2.set_index(['num1', 'num2', 'num3'], inplace=True)

# 用df2的class值更新df1_copy中匹配的行
df1_copy.update(df2)

# 重置索引并转换class为整数类型
df12 = df1_copy.reset_index().astype({'class': int})
print(df12)

两种方法运行后都会得到你期望的结果:

num1  num2  num3  class
0     1     2     3      1
1     1     2     4      1
2     1     2     5      0
3     2     2     4      0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:14