python - 如何过滤包含列表中任何字符串的 Pandas Dataframe 行?

标签 python pandas dataframe search filter

我的数据框具有如下值:

  A                    B
["I need avocado"   "something"]
["something"      "I eat margarina"]

我想找到符合以下条件的行:

在行的任何 列中,该列的值包含在列表中。 例如,对于列表:

["apple","avocado","bannana"]

只有这一行应该匹配: [“我需要鳄梨”“东西”]

这条线不起作用:

dataFiltered[dataFiltered[col].str.contains(*includeKeywords)]

返回:

{TypeError}unsupported operand type(s) for &: 'str' and 'int'

我该怎么办?

最佳答案

设置

df = pd.DataFrame(dict(
    A=['I need avocado', 'something', 'useless', 'nothing'],
    B=['something', 'I eat margarina', 'eat apple', 'more nothing']
))
includeKeywords = ["apple", "avocado", "bannana"]

问题

                A                B
0  I need avocado        something  # True 'avocado' in A
1       something  I eat margarina
2         useless        eat apple  # True 'apple' in B
3         nothing     more nothing

解决方案


df[df.stack().str.contains('|'.join(includeKeywords)).any(level=0)]

                A          B
0  I need avocado  something
2         useless  eat apple

详情

这会生成一个 regex 搜索字符串。在 regex 中,'|' 表示 or。所以对于 regex 搜索,这表示匹配 'apple''avocado''bannana'

kwstr = '|'.join(includeKeywords)
print(kwstr)

apple|avocado|bannana

堆叠会压扁我们的DataFrame

df.stack()

0  A     I need avocado
   B          something
1  A          something
   B    I eat margarina
2  A            useless
   B          eat apple
3  A            nothing
   B       more nothing
dtype: object

幸运的是,pandas.Series.str.contains 方法可以处理 regex 并且它会生成一个 bool 值 Series

df.stack().str.contains(kwstr)

0  A     True
   B    False
1  A    False
   B    False
2  A    False
   B     True
3  A    False
   B    False
dtype: bool

此时我们可以巧妙地使用 pandas.Series.any,建议它只关心 level=0

mask = df.stack().str.contains(kwstr).any(level=0)
mask

0     True
1    False
2     True
3    False
dtype: bool

通过使用 level=0,我们在生成的 Series 中保留了原始索引。这使得它非常适合过滤 df

df[mask]

                A          B
0  I need avocado  something
2         useless  eat apple

关于python - 如何过滤包含列表中任何字符串的 Pandas Dataframe 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941100/

相关文章:

python - pd.to_numeric 将整个系列转换为 NaN

android - 从 adb logcat 捕获输出

python - 如何内省(introspection) App Engine 数据存储模型?

python - 不止一个条件满足numpy select

python - 如何在多列上重新采样并创建 value_counts() 和 count() 的时间序列?

python - 如何减去 Pandas Dataframe 中的两个日期时间值

r - 按行而不是列取消列出数据框

python - 我可以调整这个seaborn 热图中颜色条的比例吗?

python - 如何在 Windows python 3.4 上安装 numpy?

python - 在字典中按值返回键