pandasflat

Calculate % change in flat tables


From df1 I would like to calculate the percentage change from, which should give df2. Would you please assist me?

df1

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

df2

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

Thank you


Solution

  • Use groupby and pct_change:

    df1['%_delta'] = df1.groupby('FN')['AuM'].pct_change()
    print(df1)
    
    # Output:
           Date FN AuM %_delta
    0  01012021  A  10     NaN
    1  01012021  B  20     NaN
    2  01012021  A  12    0.20
    3  01012021  B  23    0.15