[英]Python - Check if a value in a df1 column is present in df2 column
I have two dataframes, 我有两个数据帧,
df1 DF1
ID Key
1 A
2 B
3 C
4 D
df2 DF2
ID Key
1 D
2 C
3 B
4 E
Now, if the key in the df1 is found in df2 then the new column will have a value found else not found 现在,如果在df2中找到df1中的键,则新列将具有找不到的值
the df1 with the output dataframe becomes, 带输出数据帧的df1成为,
ID Key Result
1 A Not Found
2 B Found
3 C Found
4 D Found
How can we do this using Pandas? 我们怎么能用熊猫这样做呢? It's not a join/concat/merge by ID.
这不是ID的连接/连接/合并。
Use numpy.where
with isin
: 使用
numpy.where
与isin
:
df1['Result'] = np.where(df1['Key'].isin(df2['Key']), 'Found', 'Not Found')
print (df1)
ID Key Result
0 1 A Not Found
1 2 B Found
2 3 C Found
3 4 D Found
Another way to do using merge
and np.where
使用
merge
和np.where
另一种方法
df1['Result'] = np.where(pd.merge(df1,df2,
on='key',
suffixes=('_x', '_match'),
how='left')['id_match'].fillna('Not Found')!='Not Found','Found','Not Found')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.