数据类型为字符串的数据框列文本包含句子,我希望提取包含某些单词的行,无论它们出现的位置如何。
例如:
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
上面抛出了一个错误。
我知道对于或条件我们可以写 -
df = df[df['cleantext'].str.contains('cat | mouse')].reset_index()
但是我想提取猫和老鼠都存在的行
预期输出 -
Column
Cat and mouse are the born enemies
最佳答案
这是一种方法,也适用于多个单词:
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
关于python - 如何识别包含多个单词的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56008377/