Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting previous row values from within pandas apply() function

Tags:

python

pandas

import pandas as pd

def greater_or_less(d):
    if d['current'] > d['previous']:
        d['result']="Greater"
    elif d['current'] < d['previous']:
        d['result']="Less"
    elif d['current'] == d['previous']:
        d['result']="Equal"
    else:
        pass
    return d

df=pd.DataFrame({'current':[1,2,2,8,7]})

# Duplicate the column with shifted values
df['previous']=df['current'].shift(1)

df['result']=""

df=df.apply(greater_or_less,axis=1)

The result is:

   current  previous   result
        1       NaN         
        2         1  Greater
        2         2    Equal
        8         2  Greater
        7         8     Less

I'd then drop the previous column as it's no longer needed. Ending up with:

   current   result
        1         
        2  Greater
        2    Equal
        8  Greater
        7     Less

How can I do this without adding the extra column?

What i'd like to do, is know how to reference the previous row's value from within the greater_or_less function.

like image 374
zio Avatar asked Feb 18 '26 03:02

zio


1 Answers

Use diff() method:

import pandas as pd
import numpy as np
df=pd.DataFrame({'current':[1,2,2,8,7]})
np.sign(df.current.diff()).map({1:"Greater", 0:"Equal", -1:"Less"})
like image 86
HYRY Avatar answered Feb 20 '26 15:02

HYRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!