在 Python 的一列或多列中搜索多个字符串时,如何将 OR 运算符用于 str.contains 函数?

How can I use the OR operator for the str.contains funtion when searching for multiple strings in a column or in multiple columns in Python?

我正在尝试使用 Python 中的 str.contains 函数在列中搜索 'keyword'。

我成功地在一栏中查找了一个关键字。

但是,我需要的是: - 在一列中搜索多个关键字

我正在使用以下示例数据集:

Employee    Employee ID     Category    Comments
Jack        11234           Holiday     Holiday trip
Ben         1921            Business    Business trip
John        233535          Other       Other trip
Pete        892230          Other       Other trip

通过使用以下代码:

df[df['Category'].str.contains("holiday", case=False)]

我已成功获得以下结果:

Employee    Employee ID         Category        Comments
Jack            11234           Holiday         Holiday trip

但是,我想搜索关键字假日或商务。使用 OR 运算符我似乎无法使其工作。关于扩展代码的任何建议,以便我可以搜索假期或商务这两个词?

最终结果需要如下所示(意思是 returns 行在类别列中有关键字 Holiday OR Business):

Employee    Employee ID     Category    Comments
Jack        11234           Holiday     Holiday trip
Ben         1921            Business    Business trip

下一部分是我想在多个列中搜索关键字。我尝试了以下代码:

df[df['Category'].str.contains("holiday", case=False)] | 
df[df['Comments'].str.contains("holiday", case=False)]

但不幸的是,这并没有产生预期的结果。

非常感谢您的见解!

您在str.contains中使用|表示'or':

df[df['Category'].str.contains('holiday|business', case=False)]

有关详细信息,请参阅 docs