Pandas Efficient Filtering: Same filter condition on multiple columns

Viewed 271

Say I have the data below:

df = pd.DataFrame({'col1': [1, 2, 1],
                   'col2': [2, 4, 3],
                   'col3': [3, 6, 5],
                   'col4': [4, 8, 7]})

Is there a way to use list comprehensions to filter data efficiently? For example, if I wanted to find all cases where col2 was even OR col3 was even OR col 4 was even, is there a simpler way than just writing this?

df[(df['col2'] % 2 == 0) | (df['col3'] % 2 == 0) | (df['col4'] % 2 == 0)]

It would be nice if I could pass in a list of columns and the condition to check.

1 Answers

df[(df[cols] % 2 == 0).any(axis=1)]

where cols is your list of columns

Related