Python Forum
Combine groupby() and shift() in pandas - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Combine groupby() and shift() in pandas (/thread-31010.html)



Combine groupby() and shift() in pandas - rama27 - Nov-17-2020

Hi,
I have a following issue. I need to compute lagged means per groups in my dataframe. See following example:

import pandas as pd

df = pd.DataFrame(data={ 'name':["a","a","a","b","b","c" ] , 'value':[5,4,3,1,2,1] , 'round':[1,2,3,1,2,1 ]})
Desired output is:

df = pd.DataFrame(data={ 'name':["a","a","a","b","b","c" ] , 'value':[5,4,3,1,2,1] , 'round':[1,2,3,1,2,1], 'mean_per_round':[NaN,5,4.5,NaN,1.5,NaN]})
I tried this, but it shifts all values, not only within a group:

df['mean_per_round'] = df.groupby(['name'])['value'].expanding().mean().shift(1).values
Any suggestions, please? Thanks a lot.