I have a dataframe looks like:
user_id date balance
A 1 100
A 2 200
A 3 250
B 2 300
B 3 200
I would like to create a new column which is the difference of balance today and previous day for each user.
user_id date balance balance_previous_day
A 1 100 NaN
A 2 200 100
A 3 250 50
B 2 300 NaN
B 3 200 -100
I tried:
df.groupby (['user_id']).apply (lambda x: np.diff (x.balance, 1))
And the result will be:
user_id
A [100, 50]
B [-100]
The result is correct but I don't know how to put back the result to the dataframe.