How to extract from a dataframe rows only if values in a column are higher than values in another colum?

25 Views Asked by At

I have the following dataframe

df = pd.DataFrame({'a': [100, 200, 300, 400],
                   'b': [80, 250, 500, 350]})

print(df)

     a    b
0  100   80
1  200  250
2  300  500
3  400  350

I would like to extract the rows only if the value of the column 'a' is higher than the value of the 'b' column.

So in my example I should get as result this dataframe:

     a    b
0  100   80
3  400  350

Thanks

2

There are 2 best solutions below

0
DataSciRookie On BEST ANSWER
df = pd.DataFrame({'a': [100, 200, 300, 400],
                   'b': [80, 250, 500, 350]})

# Result
df.loc[df['a']>df['b'],:]
0
Andrej Kesely On

Try:

print(df.query("a > b"))

Prints:

     a    b
0  100   80
3  400  350