如何在Pandas中实现两DataFrame列值匹配并生成标记列?
为DataFrame添加匹配标记列
需求说明
检查第二个DataFrame的「Another header」列值是否存在于第一个DataFrame的同列中,存在则在第二个DataFrame新增「match」列并赋值1,不存在则赋值0。
示例数据
第一个DataFrame(df1):
| A header | Another header |
|---|---|
| First | apple |
| Second | orange |
| third | banana |
| fourth | tea |
第二个原始DataFrame(df2):
| A header | Another header |
|---|---|
| First | sheet |
| Second | chair |
| third | apple |
| fourth | orange |
实现代码
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 header | Another header | match |
|---|---|---|
| First | sheet | 0 |
| Second | chair | 0 |
| third | apple | 1 |
| fourth | orange | 1 |
代码说明
df2['Another header'].isin(df1['Another header']):检查df2的列值是否在df1的对应列中,返回布尔值Series(存在为True,不存在为False).astype(int):将布尔值转换为整数,True转为1,False转为0
内容的提问来源于stack exchange,提问作者Krish
相关产品推荐
相关产品推荐

