Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter pandas dataframe with more than 2 conditions?

I have a dataframe with multiple columns. I want to filter the dataframe based on two columns. For one column there is one condition and for the other column there are 3 conditions.

This code for the one condition in each column works fine:

filtered_df = df[(df['col1'] == 'cond1') & (df['col2'] == 'cond2)]

When I expand this to 3 conditions for the second column I get an empty dataframe as a result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

filtered_df = df[(df['col1'] == 'cond1') & (df['col2'] == 'cond2) & (df['col2'] == 'cond3) & (df['col2'] == 'cond4)]

How can I filter with more than 2 conditions?

>Solution :

filtered_df = df[(df['col1'] == 'cond1') & (df['col2'] == 'cond2) & (df['col2'] == 'cond3) & (df['col2'] == 'cond4)]

please be careful… in your code there are four condition that contradictory:

col2 can not be cond2 and cond3 and cond4 at same time

so you must use or:

filtered_df = df[(df['col1'] == 'cond1') & ((df['col2'] == 'cond2') | (df['col2'] == 'cond3') | (df['col2'] == 'cond4'))]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading