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

filter dataframe based on 2 conditions

I have following example dataframe:

df = pandas.DataFrame({'col1': [A, A, B, A, B, B, A, B, B, A], 'col2': [0, 0, 1, 1, 0, 1, 0, 0, 0, 0]})

Now, I would like to create a second dataframe containing only the rows from df where:
col1 – A matches col2: 0 and
col1 – B matches col2: 1

df2 = pandasDataFrame({'col1' : [A, A, B, B, A, A], 'col2' : [0, 0, 1, 1, 0, 0]})

I have tried with query, but it is only working on one condition, if I separate condition pair in paranthesis, I get an empty dataframe.

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

Thank you in advance for your help!

>Solution :

You could use create a boolean mask and filter:

out = df[(df['col1'].eq('A')&df['col2'].eq(0)) | (df['col1'].eq('B') & df['col2'].eq(1))]

Output:

  col1  col2
0    A     0
1    A     0
2    B     1
5    B     1
6    A     0
9    A     0
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