MJA
MJA

Reputation: 397

Pandas: Check if column value is smaller than any previous column value

I want to check if any value of column 'c' is smaller than all previous column values. In my current approach I am using pandas diff(), but it let's me only compare to the previous value.

import pandas as pd

df = pd.DataFrame({'c': [1, 4, 9, 7, 8, 36]})

df['diff'] = df['c'].diff() < 0

print(df)

Current result:

    c   diff
0   1  False
1   4  False
2   9  False
3   7   True
4   8  False
5  36  False

Wanted result:

    c   diff
0   1  False
1   4  False
2   9  False
3   7   True
4   8   True
5  36  False

So row 4 should also result in a True, as 8 is smaller than 9.

Thanks

Upvotes: 3

Views: 6056

Answers (1)

Zito Relova
Zito Relova

Reputation: 1041

This should work:

df['diff'] = df['c'] < df['c'].cummax()

Output is just as you mentioned:

    c   diff
0   1  False
1   4  False
2   9  False
3   7   True
4   8   True
5  36  False

Upvotes: 9

Related Questions