python - 使用 str.contains 选择包含搜索词列表中所有字符串的数据帧行

标签 python pandas dataframe

我有一个 Pandads 数据框,其中一列(“已处理”)是一个字符串,其中包含一些不同长度的预处理文本。

我想使用任意长度的关键字列表进行搜索,以仅返回字符串“processed”包含列表中所有元素的行的已处理注释。

当然,我可以单独搜索这些术语,例如:

words = ['searchterm1', 'searchterm2']
notes = df.loc[(df.processed.str.contains(words[0])) & (df.processed.str.contains(words[1]))].processed

但这似乎效率低下,并且根据我使用的搜索词的数量需要不同的代码。

我正在寻找的是......

notes = (df.loc[[(df.processed.str.contains(words[i])) for i in range(len(words))]]).processed

其中包括

“searchterm1 foo bar searchterm”

但不包括

“foo bar searchterm1”

“searchterm2”

但这不起作用 - loc 不支持生成器对象或列表作为输入。

那么查找包含多个子字符串的字符串的最佳方法是什么?谢谢!

最佳答案

示例数据:

df = pd.DataFrame(data=[[1,'a', 3],
                   [1,'b', 4],
                   [2,'c', 22],
                   [2,'s', 3],
                   [2,'f', 3],
                   [1,'d', 56]], 
             columns = ['group', 'value', 'value2'])

words = ['two', 'three', 'two']

输出:

  processed
0       one
1       two
2     three
3   one one
4  two, one

我修改了你的原始代码:

notes = df.loc[sum([df.processed.str.contains(word) for word in words]) > 0]

输出:

  processed
1       two
2     three
4  two, one

关于python - 使用 str.contains 选择包含搜索词列表中所有字符串的数据帧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52275409/

相关文章:

python - groupby.agg 中的本福德定律测试函数

dataframe - pyspark 数据帧总和

pandas - 用pandas.to_excel将float值截断到小数点后8位

python - 从元组中删除元素时额外的空元素

python - 当一个模块被导入两次时会发生什么?

Python:绘制 3D 曲面时出现 AttributeError

python - 使用 python statsmodels 修复summary_col 中的标签外生变量

Python:在脚本中运行脚本时找不到模块

python - 单个 Dataframe 单元格中系列的最大值

python - 在进行 pandas 合并时,用唯一的 "na"标识符填充 "na"值