aiman khalid
aiman khalid

Reputation: 147

how to return a dataframe if one of rows in column match certain value

i have dataframe that i want it to return me a dataframe if one of the values is high

df

a     b    c     d    e    f 
high low  high  low  high low
low  low  low   low  low  high
low  low  low   low  low  low

I know how to do it if we filter it in column

df[df[a]=="high"]

If i tried to loop the process but it won't work

for column in df.columns:
    df_high=df[df[column]=="high"]

df_high return 0 rows. Expected result:

 a    b   c    d   e    f
high low high low high low
low  low low  low low  high

Upvotes: 1

Views: 436

Answers (2)

Michele Cavazza
Michele Cavazza

Reputation: 121

I would do like this

df = pd.DataFrame({'a':['high', 'low', 'low'], 'b':['low', 'high', 'low']})
df.loc[(df=='high').sum(axis=1) > 0]

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

Use, DataFrame.eq along with DataFrame.any along axis=1 to create a boolean mask then use this mask to filter out the rows in dataframe:

mask = df.eq('high').any(axis=1)
df1 = df[mask]

Result:

# print(df1)

     a    b     c    d     e     f
0  high  low  high  low  high   low
1   low  low   low  low   low  high

Upvotes: 2

Related Questions