Search code examples
pythonpandasjupytervelocitydifference

Add column with previous values by group


I have got the following dataframe:

lst=[['01012021','A',10],['01012021','B',20],['02012021','A',12],['02012021','B',23]]
df2=pd.DataFrame(lst,columns=['Date','FN','AuM'])

I would like to add a column with the previous values by FN. As a result I should get the following dataframe:

df2=pd.DataFrame(lst,columns=['Date','FN','AuM','PreviousValues'])

Would you please help me?


Solution

  • use shift

    df2['PreviousValues'] = df2['FN'].shift()
    

    output:

    
            Date       FN   AuM PreviousValues
    0       01012021    A   10  NaN
    1       01012021    B   20  A
    2       02012021    A   12  B
    3       02012021    B   23  A