Python 检查一个数据框中的值是否存在于另一个数据框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50449088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value from one dataframe exists in another dataframe
提问by toceto
I have 2 dataframes.
我有 2 个数据框。
Df1 = pd.DataFrame({'name': ['Marc', 'Jake', 'Sam', 'Brad']
Df2 = pd.DataFrame({'IDs': ['Jake', 'John', 'Marc', 'Tony', 'Bob']
I want to loop over every row in Df1['name']
and check if each name is somewhere in Df2['IDs']
.
我想遍历每一行Df1['name']
并检查每个名称是否在Df2['IDs']
.
The result should return 1 if the name is in there, 0 if it is not like so:
如果名称在那里,结果应该返回 1,如果不是这样,则返回 0:
Marc 1
Jake 1
Sam 0
Brad 0
Thank you.
谢谢你。
回答by piRSquared
Use isin
用 isin
Df1.name.isin(Df2.IDs).astype(int)
0 1
1 1
2 0
3 0
Name: name, dtype: int32
Show result in data frame
在数据框中显示结果
Df1.assign(InDf2=Df1.name.isin(Df2.IDs).astype(int))
name InDf2
0 Marc 1
1 Jake 1
2 Sam 0
3 Brad 0
In a Series object
在 Series 对象中
pd.Series(Df1.name.isin(Df2.IDs).values.astype(int), Df1.name.values)
Marc 1
Jake 1
Sam 0
Brad 0
dtype: int32
回答by zipa
This should do it:
这应该这样做:
Df1 = Df1.assign(result=Df1['name'].isin(Df2['IDs']).astype(int))
回答by YOBEN_S
By using merge
通过使用 merge
s=Df1.merge(Df2,left_on='name',right_on='IDs',how='left')
s.IDs=s.IDs.notnull().astype(int)
s
Out[68]:
name IDs
0 Marc 1
1 Jake 1
2 Sam 0
3 Brad 0
回答by jpp
This is one way. Convert to set for O(1) lookup and use astype(int)
to represent Boolean values as integers.
这是一种方式。转换为 O(1) 查找设置并用于astype(int)
将布尔值表示为整数。
values = set(Df2['IDs'])
Df1['Match'] = Df1['name'].isin(values).astype(int)