Ipad shak
Ipad shak

Reputation: 33

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?

I am trying to use the str.contains function in Python to search for a 'keyword' within a column.

I have succeeded with looking up one key word in one column.

However, what I would need is the following: - Search for multiple keywords in one column

I am using the following sample dataset:

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

By using the following code:

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

I have succeed in getting the following result:

Employee    Employee ID         Category        Comments
Jack            11234           Holiday         Holiday trip

However, I would like to search for keywords holiday OR business. Using the OR operator I cannot seem to make it work. Any suggestions on expanding the code so I can look search for both words holiday OR business?

The end result would then need to look like this (meaning returns rows that have keyword Holiday OR Business in column Category):

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

The next part is that I would like to search for the keyword in multiple columns. I tried the following code:

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

But this unfortunately didn't yield the expected results.

Many thanks for your insights!

Upvotes: 3

Views: 3390

Answers (1)

AAA
AAA

Reputation: 3670

You use | to represent 'or' in str.contains:

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

For more infomation, see the docs.

Upvotes: 5

Related Questions