Reputation: 86
I have a dataframe with 30 columns, each cell containing a 1 or 0.
I would like to filter the dataframe for where any 1 of 4 specific columns == 1.
Right now, it would have to be chained masks like:
df[(df['col1'] == 1) | (df['col2'] == 1) | (df['col3'] == 1) | (df['col4'] == 1)]
Is there a simpler and scalable way to do this? Something like making a list of the column names, and using slice notation to check all boolean conditions in one go?:
col_list = ['col1', 'col2', 'col3', 'col4']
df[df[col_list] == 1]
Upvotes: 1
Views: 191
Reputation: 419
Try this:
col_df=list(df) # get all the column names
filtered_df=df[df[col_df].any(1)]
Upvotes: 2