Pandas 检查一行数据帧的值是否不包含在另一个数据帧的列中

Pandas 检查一行数据帧的值是否不包含在另一个数据帧的列中,pandas,Pandas,我想通过“if”条件检查一个数据帧中的行的值是否不包含在另一个数据帧的特定列中 如果我的数据帧是: df1: col1 col2 0 a e 1 b f 2 c g 3 d h df2: col1 col2 0 a y 1 v u 2 x z 3 w t 我想遍历df1中col1中的每一行,并检查该值是否不包含在df2的col1中 我目前的代码是: for row, i in df1.iterrows():

我想通过“if”条件检查一个数据帧中的行的值是否不包含在另一个数据帧的特定列中

如果我的数据帧是:

df1:
   col1 col2
0   a   e
1   b   f
2   c   g
3   d   h

df2:

   col1 col2
0   a   y
1   v   u
2   x   z
3   w   t
我想遍历df1中col1中的每一行,并检查该值是否不包含在df2的col1中

我目前的代码是:

 for row, i in df1.iterrows():
    for row, j in df2.iterrows():
       if i.col1 not in j.col1:
          print("blu")
现在,即使df1的col1中的值包含在df2的col1中,代码也将进入if条件

任何帮助都将不胜感激。

使用
isin

df1.col1.isin(df2.col1)

0     True
1    False
2    False
3    False
Name: col1, dtype: bool

在pandas中,最好避免使用
iterrows
循环,因为循环速度很慢。因此,最好使用非常快速的矢量化
pandas
numpy
函数

如果需要,请检查列中是否不存在-与
~
一起用于反转布尔掩码:

mask = ~df1.col1.isin(df2.col1)
print (mask)

0    False
1     True
2     True
3     True
Name: col1, dtype: bool
替代解决方案是使用:


如果需要按行检查,请使用
=或:

或:

如果可以通过掩码创建新列,请使用:

差异在稍微不同的
数据帧中表现得更好:

print (df1)
  col1 col2
0    a    e
1    b    f
2    c    g
3    d    h

print (df2)
  col1 col2
0    a    y
1    v    u
2    d    z <- change value to d
3    w    t


mask = df1.col1 != df2.col1
print (mask)
0    False
1     True
2     True
3     True
Name: col1, dtype: bool
Numpy解决方案显然更快:

In [23]: %timeit (~df1.col1.isin(df2.col1))
The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 198 µs per loop

In [24]: %timeit (~np.in1d(df1.col1,df2.col1))
The slowest run took 9.25 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 42.5 µs per loop

谢谢你,回答得很好。所有的解决方案都用于确定某个值是否在列中,但当我尝试将其与“if”这样的条件一起使用时,我得到了以下错误:序列的真值是不明确的。使用a.empty、a.bool()、a.item()、a.any()或a.all()。如果通过
if mask.any()至少有一个值为true,则需要为chech添加any。打印“至少一个true”
也可以更好地解释它的答案。
mask = df1.col1.values != df2.col1.values
print (mask)
[False  True  True  True]
df1['new'] = np.where(mask, 'a', 'b')
print (df1)
  col1 col2 new
0    a    e   b
1    b    f   a
2    c    g   a
3    d    h   a
print (df1)
  col1 col2
0    a    e
1    b    f
2    c    g
3    d    h

print (df2)
  col1 col2
0    a    y
1    v    u
2    d    z <- change value to d
3    w    t


mask = df1.col1 != df2.col1
print (mask)
0    False
1     True
2     True
3     True
Name: col1, dtype: bool
mask = ~df1.col1.isin(df2.col1)
print (mask)
0    False
1     True
2     True
3    False
Name: col1, dtype: bool
In [23]: %timeit (~df1.col1.isin(df2.col1))
The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 198 µs per loop

In [24]: %timeit (~np.in1d(df1.col1,df2.col1))
The slowest run took 9.25 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 42.5 µs per loop