With a list of columns, filter a data frame with at least one of the columns meeting a condition?

时间:2019-04-17 02:38:16

标签: python pandas filter

Say that I have a dataframe with 50 columns. Of these 50 columns, I have a list of 6 columns that are of interest.

list_cols = ['a', 'b', 'c', 'd', 'e', 'f']

I want to filter the dataframe such that at least one of these 6 cols must be <= 5. How would I go about doing this without having to tediously write something like:

df.loc[(df['a'] <= 5) | 
       (df['b'] <= 5) |
       (df['c'] <= 5) |
       (df['d'] <= 5) |
       (df['e'] <= 5) |
       (df['f'] <= 5)]

Or writing a for loop on each column, concatenating, and dropping duplicate rows? Is there another option? Thanks.

2 个答案:

答案 0 :(得分:1)

Just using any

df[df[list_cols].le(5).any(1)]

答案 1 :(得分:1)

You can also use min

df[df[list_col].min(axis=1).le(5)]