mac389
mac389

Reputation: 3133

Select Rows in Pandas Based on "OR" over Columns

I want to select rows based on whether a certain value occurs at least once in one of a few columns. I could only find examples where one chose rows based on one column containing certain values.

How would I chose a and b but not c because 7 occurred in [Field1, Field2, Field3] for a and b but not c.

Label Field1 Field2 Field3 ... Other Columns of no Interest
a        7 
b       10      7
c              10

Upvotes: 0

Views: 33

Answers (2)

asongtoruin
asongtoruin

Reputation: 10359

If you want to retain all columns of your data, you could instead do:

df[df[['Field1', 'Field2', 'Field3']].eq(7).any(axis='columns')]

Which would give you (depending on where your values are located, it's unclear from the example):

    Label   Field1  Field2  Field3
0       a        7     NaN     NaN
1       b       10     7.0     NaN

Upvotes: 1

BENY
BENY

Reputation: 323226

You can do melt

df.melt('Label').loc[lambda x : x.value==7].Label
Out[14]: 
0    a
4    b
Name: Label, dtype: object

Upvotes: 2

Related Questions