【问题标题】:'and' operator in string.containsstring.contains 中的“和”运算符
【发布时间】:2024-01-22 11:47:01
【问题描述】:

我有一个熊猫系列,我正在以这种方式应用字符串搜索

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

这给了我真/假列表,具体取决于字符串“test1”是否包含在“column_name”列中。

但是我无法测试两个字符串,我需要检查两个字符串是否都存在。类似的东西

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

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

【问题讨论】:

    标签: python string pandas series


    【解决方案1】:

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

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

    如果您想测试任何一个单词,那么以下方法将起作用:

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

    【讨论】:

      【解决方案2】:
      all( word in df['column_name'] for word in ['test1', 'test2'] )
      

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

      【讨论】:

      • 您可以通过删除最外面的方括号将列表理解更改为更高效的生成器。然后不会创建新列表,all 将能够短路。
      • 'all' 给了我一个真/假值。我需要 colubomn 中的每个条目,无论 test1 和 test2 是否都存在。因此,如果 column_name 的长度为 400,我想知道其中有多少具有“test1”以及其中有多少是“test2”。到目前为止,EdChums 的回答最有意义
      • 您的问题表明您需要同时检查两者,我假设您想同时进行,因为您使用了 and 运算符而不是 or
      【解决方案3】:

      忽略'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 运算符充当“真相决定者”,并且对字符串有轻微奇怪的行为。从本质上讲,返回值是最后一个被评估的值,无论它是一个字符串还是其他。看看这个行为:

      >>> a = 'test1'
      >>> b = 'test2'
      >>> c = a and b
      >>> c is a
      False
      >>> c is b
      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
      

      【讨论】:

      • 感谢在“test2”中添加了缺少的引号
      • 感谢您的详细解答。我在这方面学到了很多东西,但不确定我是否可以直接使用它来实现我想要实现的目标
      • 看一下第三个代码段。那应该执行您希望它执行的操作。
      • 谢谢大家。如何计算 column_name 条目中的匹配数和未命中数。我在 EdChums 解决方案上使用 vale_counts() 命令,它正在工作。
      【解决方案4】:

      您想知道test1 AND test2 是否在列中。

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

      【讨论】:

      • 感谢您向我介绍 any(),但是在此要求中,我需要知道 column_name 中有多少条目匹配,有多少没有匹配