Skip to main content
 首页 » 编程设计

python之string.contains 中的“和”运算符

2025年05月04日11sky-heaven

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

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

根据字符串“test1”是否包含在列“column_name”中,这会给出真/假列表。

但是我无法在需要检查两个字符串是否存在的地方测试两个字符串。有点像

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

这似乎行不通。任何建议都会很棒。

请您参考如下方法:

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

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

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

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