简体   繁体   中英

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

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.

只是使用any

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

您也可以使用min

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM