'and' string.contains 中的运算符

'and' operator in string.contains

我有一个 pandas 系列,我在其中以这种方式应用字符串搜索

df['column_name'].str.contains('test1')

根据字符串 'test1' 是否包含在列 'column_name' 中,这给了我 true/false 列表。

但是我无法测试两个字符串,我需要检查两个字符串是否都存在。像

  df['column_name'].str.contains('test1' and 'test2')

这似乎不起作用。任何建议都会很棒。

all( word in df['column_name'] for word in ['test1', 'test2'] )

这将测试字符串中存在的任意数字或单词

不,您必须创建 2 个条件并使用 & 并根据运算符优先级将条件括起来:

(df['column_name'].str.contains('test1')) & (df['column_name'].str.contains('test2))

如果您想测试其中任何一个词,则以下方法可行:

df['column_name'].str.contains('test1|test2')

忽略 'test2 中缺少的引号,'and' 运算符是布尔逻辑运算符。它不会连接字符串,也不会执行您认为它执行的操作。

>>> 'test1' and 'test2'
'test2'
>>> 'test1' or 'test2'
'test1'
>>> 10 and 20
20
>>> 10 and 0
10
>>> 0 or 20
20
>>> # => and so on...

这是因为 andor 运算符的功能与 'truth deciders' 相同,并且对字符串有轻微的奇怪行为。本质上,return 值是最后计算的值,无论它是字符串还是其他。看看这个行为:

>>> a = 'test1'
>>> b = 'test2'
>>> c = a and b
>>> c is a
False
>>> c is b
True

后一个值被分配给我们赋予它的变量。您正在寻找的是一种遍历列表或字符串集并确保所有结果都为 true 的方法。为此,我们使用 all(iterable) 函数。

if all([df['column_name'].contains(_) for _ in ['test1', 'test2']]):
    print("All strings are contained in it.")
else:
    print("Not all strings are contained in it.")

假设情况属实,以下是您将收到的示例:

>>> x = [_ in df['column_name'] for _ in ['test1', 'test2']
>>> print(x)
[True, True] # => returns True for all()
>>> all(x)
True
>>> x[0] = 'ThisIsNotIntTheColumn' in df['column_name']
>>> print(x)
[False, True]
>>> all(x)
False

您想知道 test1 AND test2 是否在列中的某个位置。

所以df['col_name'].str.contains('test1').any() & df['col_name'].str.contains('test2').any().