Pandas:在两个数据帧中查找匹配的行(不使用“合并”)

ixa*_*xim 2 python matching dataframe pandas isin

假设我有这两个数据框,其列数相同,但行数可能不同:

tmp = np.arange(0,12).reshape((4,3))
df = pd.DataFrame(data=tmp) 

tmp2 = {'a':[3,100,101], 'b':[4,4,100], 'c':[5,100,3]}
df2 = pd.DataFrame(data=tmp2)

print(df)
   0   1   2
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11

print(df2)
     a    b    c
0    3    4    5
1  100    4  100
2  101  100    3
Run Code Online (Sandbox Code Playgroud)

我想验证 的行是否df2与 的任何行匹配 df,也就是说,我想获得一系列(或数组)布尔值来给出以下结果:

0     True
1    False
2    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)

我认为类似的isin方法应该有效,但我得到了这个结果,这导致了一个数据框并且是错误的:

print(df2.isin(df))
       a      b      c
0  False  False  False
1  False  False  False
2  False  False  False
Run Code Online (Sandbox Code Playgroud)

作为限制,我希望不使用该merge方法,因为我所做的实际上是在应用合并本身之前检查数据。感谢您的帮助!

sop*_*les 5

您可以使用numpy.isin,它将比较数组中的所有元素,并为每个数组的每个元素返回Trueor 。False

然后在每个数组上使用,如果所有元素都为 true,all()则函数返回时将获得所需的输出:True

>>> pd.Series([m.all() for m in np.isin(df2.values,df.values)])

0     True
1    False
2    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)

正在发生的事情的细分:

# np.isin
>>> np.isin(df2.values,df.values)

Out[139]: 
array([[ True,  True,  True],
       [False,  True, False],
       [False, False,  True]])

# all()
>>> [m.all() for m in np.isin(df2.values,df.values)]

Out[140]: [True, False, False]

# pd.Series()
>>> pd.Series([m.all() for m in np.isin(df2.values,df.values)])

Out[141]: 
0     True
1    False
2    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)