gasabr
gasabr

Reputation: 75

Filter pd.DataFrame rows by list of the columns

I need to select rows where value in one of the columns is not equal to 0. Here is the code:

tmp = train[(train['col1'] > 0) | (train['col2'] > 0) |
        (train['col3'] > 0) | (train['col4'] > 0) |
        (train['col5'] > 0)]

How can I accomplish the same result by iterating over the list of columns, e.g. ['col1', 'col2', ..., 'col5']?

Upvotes: 0

Views: 65

Answers (1)

Allen Qin
Allen Qin

Reputation: 19947

#use .any to check if any of the elements in a row is greater than 0.
train = train[(train>0).any()]

#if only need to check certain columns, this should work.
train[(train[['col1', 'col2', ..., ]]>0).max(1)]

Upvotes: 2

Related Questions