Skip to content
Advertisement

How to use a loop to check multiple conditions on multiple columns to filter a dataframe in Python

I have a list containing names of the columns of a dataframe.

x = ['USPR', 'ESA', 'OSFI', 'APRA']

The values for these columns are either ‘Yes’ or ‘No’.

I want to filter out rows that’d have any of the columns having ‘Yes’. I want to use maybe a for loop to iterate through the list because the list is created from user input. So instead of having a static check like below:

df = df[(df['USPR'] == 'Yes') | (df['ESA'] == 'Yes') | (df['OSFI'] == 'Yes') | (df['APRA'] == 'Yes')]

I’m wondering how to make this dynamic using a loop, i.e. number of the conditions checked would be equal to the length of x. Or any other suggestion to achieve the outcome would also be appreciated.

Much thanks.

For the below sample dataframe:

enter image description here

I’m supposed to get the filtered dataframe as below:

enter image description here

Advertisement

Answer

Try this to remove all the rows where all values are “no”.

original df:

USPR ESA OFI
yes no yes
no yes yes
no no no
df = df[(df != "no").any(axis=1)]

Output:

USPR ESA OFI
yes no yes
no yes yes
Advertisement