【问题标题】:How to identify the string where it contains multiple words [duplicate]如何识别包含多个单词的字符串[重复]
【发布时间】:2019-09-24 06:38:51
【问题描述】:

数据类型字符串的数据框列文本包含句子,我希望提取包含某些单词的行,而不管它们出现在哪里。

例如:

Column
Cat and mouse are the born enemies
Cat is a furry pet


df = df[df['cleantext'].str.contains('cat' & 'mouse')].reset_index()
df.shape

上面是抛出一个错误。

我知道 for or condition 我们可以写 -

df = df[df['cleantext'].str.contains('cat | mouse')].reset_index()

但我想提取同时存在 cat 和 mouse 的行

预期输出 -

Column
Cat and mouse are the born enemies

【问题讨论】:

  • 如果是正则表达式,你会使用(?=.*cat)(?=.*mouse)
  • 谢谢,我也试试这个方法。

标签: python regex conditional string-search


【解决方案1】:

这是一种方法,它也适用于多个单词:

words = ['cat', 'mouse']
m = pd.concat([df.Column.str.lower().str.contains(w) for w in words], axis=1).all(1)
df.loc[m,:]

      Column
0  Cat and mouse are the born enemies

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2021-03-07
  • 2020-02-18
  • 2020-02-19
相关资源
最近更新 更多