Python: Filtering multiple conditions for ALL columns

Viewed 41

So I have a df here:

enter image description here

and I'm trying to do some filtering based on certain conditions. It works just fine when I've done this all based on one condition but I can't do the same thing as pythonically as I'd like because all search results I see work based on one specific column. That and the type of searches also include strings. What I'm trying to do is filter to find the count of how many rows have a value that's higher than a 3 AND also lower than a 7 (These are all integers so they'd have to have a 4, 5 and 6.)

Sure, with a row count of 5, I could just count but this is just a subset of a much larger data frame.

I've also already tried this resource: https://www.geeksforgeeks.org/filter-pandas-dataframe-with-multiple-conditions/

Thanks!

3 Answers

The answer I got was:

df = df[df.apply(lambda x: (x < 7) & (3 < x), axis=1)]
for col in df.columns:
    df[col] = df[col].count()

All the values are the same count, but that's fine. Thanks!

Try:

df[df.apply(lambda x: (3 < x) & (x < 7)).apply(all, axis=1)]

you can use & to compare two boolean df's

(df.gt(3) & df.lt(7)).any(axis=1)

you can also use isin() with range

l = 3
h = 7
df.isin(range(l+1,h)).any(axis=1)
Related