Nov-17-2020, 09:49 PM
Hi,
I have a following issue. I need to compute lagged means per groups in my dataframe. See following example:
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).valuesAny suggestions, please? Thanks a lot.