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

Filtering multiple columns with conditions in Pandas

I am trying to filter multiple column values by conditions but I am wondering if there’s a faster or concise way to do it without putting down one column by one column, like grouping the conditions or map().

dt = pd.DataFrame(
    {
        "Num1": [1, -2, 3, -4, 5],
        "Num2": [-1, 2, -3, 4, 5],
        "Num3": [1, -2, 3, 4, -5],
        "Zum1": [1, 2, 3, -4, 5],
        "Num5": [1, -2, 3, -4, 5]
    }
); dt

# current solution:
dt[(abs(dt["Num1"] > 2) | abs(dt["Num2"] > 2) | abs(dt["Num3"] > 2)) & (dt['Zum1'] > 2)]

# expected outcome
   Num1  Num2  Num3  Zum1  Num5
2     3    -3     3     3     3
4     5     5    -5     5     5

>Solution :

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

If there is multiple conditions for compare by same value is possible use:

dt = dt[dt[['Num1','Num2','Num3']].abs().gt(2).any(1) & (dt['Zum1'] > 2)]
print (dt)
   Num1  Num2  Num3  Zum1  Num5
2     3    -3     3     3     3
4     5     5    -5     5     5

Or if need filter all column with Num use DataFrame.filter:

dt = dt[dt.filter(like='Num').abs().gt(2).any(1) & (dt['Zum1'] > 2)]
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