筛选数据帧中的关键字/句子

2024-10-05 11:08:19 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我有一个数据帧。以下是我的数据帧示例: enter image description here

我还有一个关键字/句子列表。我想将其与“内容”列匹配,并查看是否有任何关键字或句子匹配

这就是我所做的 enter image description here

# instructions_list is just the list of keywords and key sentences 
instructions_list = instructions['Key words & sentence search'].tolist()
pattern = '|'.join(instructions_list)


bureau_de_sante[bureau_de_sante['Content'].str.contains(pattern, regex = True)]

在给我结果的同时,它也给我这个UserWarning:UserWarning:这个模式有匹配组。要实际获取组,请使用str.extract。 返回函数(self、*args、**kwargs)

enter image description here

问题:

  1. 如何防止出现userwarning
  2. 查找并查看列中是否有匹配项后,如何在新列中打印特定匹配项

Tags: 数据示例内容列表isde关键字list
1条回答
网友
1楼 · 发布于 2024-10-05 11:08:19

您正在提供一个regex来搜索数据帧。如果指令列表中有括号(就像示例中的情况一样),那么这就构成了一个匹配组。为了避免这种情况,您必须转义它们(即:在它们前面添加\,以便(Critical risk)变成\(Critical risk\))。您可能还希望转义所有特殊字符,如\ . " '

现在,您可以使用这些组从数据中提取匹配项。以下是一个例子:

df = pd.DataFrame(["Hello World", "Foo Bar Baz", "Goodbye"], columns=["text"])
pattern = "(World|Bar)"
print(df.str.extract(pattern))
#        0
# 0  World
# 1    Bar
# 2    NaN

您可以通过一个简单的赋值(例如df["result"] = df.str.extract(pattern))将此列添加到数据帧中

相关问题 更多 >

    热门问题