filter pandas where some columns contain any of the words in a list

Viewed 6159

I would like to filter a Dataframe. The resulting dataframe should contain all the rows where in any of a number of columns contain any of the words of a list.

I started to use for loops but there should be a better pythonic/pandonic way.

Example:

# importing pandas 
import pandas as pd 

# Creating the dataframe with dict of lists 
df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 
                   'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 
                   'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 
                   'Number': [3, 4, 7, 11, 5], 
                   'Age': [33, 25, 34, 35, 28], 
                   'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 
                   'Weight': [89, 79, 113, 78, 84], 
                   'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 
                   'Salary': [99999, 99994, 89999, 78889, 87779]}, 
                   index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) 


df1 = df[df['Team'].str.contains("Boston") | df['College'].str.contains('MIT')] 
print(df1) 

So it is clear how to filter columns individually that contain a particular word

further on it is also clear how to filter rows per column containing any of the strings of a list:

df[df.Name.str.contains('|'.join(search_values ))]

Where search_values contains a list of words or strings.

search_values = ['boston','mike','whatever']

I am looking for a short way to code

#pseudocode
give me a subframe of df where any of the columns 'Name','Position','Team' contains any of the words in search_values

I know I can do

df[df['Name'].str.contains('|'.join(search_values )) | df['Position'].str.contains('|'.join(search_values )) | df['Team'].contains('|'.join(search_values )) ]

but if I would have like 20 columns that would be a mess of a line of code

any suggestion?

EDIT Bonus: When looking in a list of columns i.e. 'Name','Position','Team' how to include also the index? passing ['index','Name','Position','Team'] does not work.

thanks.

I had a look to this: https://www.geeksforgeeks.org/get-all-rows-in-a-pandas-dataframe-containing-given-substring/

https://kanoki.org/2019/03/27/pandas-select-rows-by-condition-and-string-operations/

Filter out rows based on list of strings in Pandas

3 Answers

You can also stack with any on level=0:

cols_list = ['Name','Team'] #add column names
df[df[cols_list].stack().str.contains('|'.join(search_values),case=False,na=False)
   .any(level=0)]

        Name    Team Position  Number  Age Height  Weight College  Salary
ind1  Geeks  Boston       PG       3   33    6-2      89     MIT   99999
ind2  Peter  Boston       PG       4   25    6-4      79     MIT   99994
ind3  James  Boston       UG       7   34    5-9     113     MIT   89999

Do apply with any

df[[c1,c2..]].apply(lambda x : x.str.contains('|'.join(search_values )),axis=1).any(axis=1)

You can simply apply in this case:

cols_to_filter = ['Name', 'Position', 'Team']
search_values = ['word1', 'word2']

patt = '|'.join(search_values)

mask = df[cols_to_filter].apply(lambda x: x.str.contains(patt)).any(1)

df[mask]
Related