Pandas 将 1 列值与另一个数据框列进行比较,找到匹配的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51885769/
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
Pandas compare 1 columns values to another dataframe column, find matching rows
提问by Drumlord_90
I have a database that I am bringing in a SQL table of events and alarms (df1), and I have a txt file of alarm codes and properties (df2) to watch for. Want to use 1 columns values from df2 that each value needs cross checked against an entire column values in df1, and output the entire rows of any that match into another dataframe df3.
我有一个数据库,我将它引入一个 SQL 事件和警报表 (df1),我有一个警报代码和属性 (df2) 的 txt 文件要注意。想要使用来自 df2 的 1 列值,每个值都需要与 df1 中的整个列值进行交叉检查,并将任何匹配的整个行输出到另一个数据帧 df3 中。
df1 A B C D
0 100 20 1 1
1 101 30 1 1
2 102 21 2 3
3 103 15 2 3
4 104 40 2 3
df2 0 1 2 3 4
0 21 2 2 3 3
1 40 0 NaN NaN NaN
Output entire rows from df1 that column B match with any of df2 column 0 values into df3.
将 df1 中 B 列与任何 df2 列 0 值匹配的整行输出到 df3 中。
df3 A B C D
0 102 21 2 3
1 104 40 2 3
I was able to get single results using:
我能够使用以下方法获得单个结果:
df1[df1['B'] == df2.iloc[0,0]]
But I need something that will do this on a larger scale.
但我需要一些可以在更大范围内做到这一点的东西。
回答by sacuL
Method 1: merge
方法一: merge
Use merge, on B
and 0
. Then select only the df1
columns
使用merge、 onB
和0
。然后只选择df1
列
df1.merge(df2, left_on='B', right_on='0')[df1.columns]
A B C D
0 102 21 2 3
1 104 40 2 3
Method 2: loc
方法二: loc
Alternatively use loc
to find rows in df1
where B
has a match in df2
column 0
using .isin
:
或者,使用loc
找到行df1
,其中B
有一个匹配df2
列0
使用.isin
:
df1.loc[df1.B.isin(df2['0'])]
A B C D
2 102 21 2 3
4 104 40 2 3