drop row if one column is greater than another

Viewed 2988

I have the following data frame:

order_id amount records
1        2      1
2        5      10
3        20     5
4        1      3

I want to remove rows where the amount is greater than the records, the output should be:

order_id amount records
2        5      10
4        1      3

Here is what I've attempted:

 df = df.drop(
        df[df.amount > df.records].index, inplace=True)

this is removing all rows, any suggestions are welcome.

2 Answers

Simply filter by:

df = df[df['amount']<df['records']]

and you get the desired results:

    order_id    amount  records
1         2        5    10
3         4        1    3
df.loc[~df.amount.gt(df.records)]

    
    order_id    amount  records
1         2        5    10
3         4        1    3

Explanation: comparisions return a boolean:

~df.amount.gt(df.records)

0    False
1     True
2    False
3     True
dtype: bool

This returns values where amount is not greater than records.

You can use this boolean to index into the dataframe to get your desired values.

Alternatively, you could use the code below as well, without having to call on the negation (~) :

 df.loc[df.amount.le(df.records)]
Related