Search code examples
pythonpython-3.xpandasdataframepandas-apply

How to access the previous value while using DataFrame.apply in python?


this is my code

_d=pd.DataFrame([[1,'foo'],[2,'bar'],[3,'kraig'],[4,'tar']],columns=['roll no','name'],index=[100,200,300,400])

_d.apply(lambda x:print(x['roll no'],axis=1)

i want to multiply my roll no from the previous rollno, something like this

roll no   hidden logic  result
===============================
1         1*1             1
2         2*1             2
3         3*2             6
4         4*3             12

how can i do this?

i know i can do something like this

for i in range(1, len(df)):
    df.loc[i, 'result'] = df.loc[i-1, 'roll no'] * df.loc[i, 'roll no']

but the above logic wont gurantee if the result correspond to the multiplication of the previous row


Solution

  • Noooooo no for loops! This is pandas 😛

    df['hidden logic'] = df['roll no'] * df['roll no'].shift(fill_value=1)