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

如何在Pandas中实现两DataFrame列值匹配并生成标记列?

为DataFrame添加匹配标记列

需求说明

检查第二个DataFrame的「Another header」列值是否存在于第一个DataFrame的同列中,存在则在第二个DataFrame新增「match」列并赋值1,不存在则赋值0。

示例数据

第一个DataFrame(df1):

A headerAnother header
Firstapple
Secondorange
thirdbanana
fourthtea

第二个原始DataFrame(df2):

A headerAnother header
Firstsheet
Secondchair
thirdapple
fourthorange

实现代码

import pandas as pd

# 构造示例DataFrame
df1 = pd.DataFrame({
    'A header': ['First', 'Second', 'third', 'fourth'],
    'Another header': ['apple', 'orange', 'banana', 'tea']
})

df2 = pd.DataFrame({
    'A header': ['First', 'Second', 'third', 'fourth'],
    'Another header': ['sheet', 'chair', 'apple', 'orange']
})

# 添加匹配标记列
df2['match'] = df2['Another header'].isin(df1['Another header']).astype(int)

# 查看结果
print(df2)

输出结果

A headerAnother headermatch
Firstsheet0
Secondchair0
thirdapple1
fourthorange1

代码说明

  • df2['Another header'].isin(df1['Another header']):检查df2的列值是否在df1的对应列中,返回布尔值Series(存在为True,不存在为False)
  • .astype(int):将布尔值转换为整数,True转为1,False转为0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:50:27