首页 > 解决方案 > 使用字符串方法过滤列值上的行

问题描述

输入 df:

title                        desc
movie A                  It is a awesome movie with action
movie B                  Slow but intense movie.

我想过滤包含以下关键字的行:

keys =  ["awesome", "action"]

输出DF:

title                        desc
movie A                  It is a awesome movie with action

代码:

index_list = []
for index,rows in df.iterrows():
   if any(x in rows["desc"].split(" ") for x in keys) == True:
       index_list.append(index)

df = df.loc[index_list]

方法:

In each row, I am checking if any of the keywords are present after splitting the rows

这种方法效果很好,但我很想知道 pandas 中是否有任何一种衬垫可以达到同样的效果。

例子:

df.loc[df['column_name'].isin(some_values)]

标签: pythonpandas

解决方案


为什么是的,有 - pandas.Series.str.contains

idx = df['column_name'].str.contains("|".join(keys), regex=True)
df[idx]

推荐阅读