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?
CodePudding user response:
As the other answers pointed out, shift can be used to obtain adjacent values, but I think your intention is to use the previous values within a certain grouping. If that's the case, use groupby before shift.
df2['PreviousValues'] = df2.groupby('FN')['AuM'].shift()
Date FN AuM PreviousValues
0 01012021 A 10 NaN
1 01012021 B 20 NaN
2 02012021 A 12 10.0
3 02012021 B 23 20.0
CodePudding user response:
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
CodePudding user response:
Did you mean previous values of FN? If so, try to use
df2['PreviousValues'] = df2['FN'].shift(1)
