Skip to content
Advertisement

Is it possible to do “rolling mean” first and then “groupby sum” in ONE GO?

For below given working codes , is it possible to compute rolling mean first and then do groupby sum in ONE GO ? I don’t want to create calculated columns in df2 as it is resulting in lots of additional columns for each value in “Mean-1 input Value”

for window1 in df1['Mean-1 input Value']:
    df2[f"Mean {window1}"] = df2['Number'].rolling(window=window1).mean()
df3 = df2.groupby('Month').sum()

Suggestion given is working fine for one input value , want to compute it for another input value. Working code for 2 input value as given below. Request to guide.

for window1 in df1['Mean-1 input Value']:
    df2[f"Mean {window1}"] = df2['Number'].rolling(window=window1).mean()
for window2 in df1['Mean-2 input Value']:
    df2[f"Mean {window2}"] = df2['Number'].rolling(window=window2).mean()

df3 = df2.groupby('Month').sum()

Advertisement

Answer

I think yes, use:

df3 = (df2.assign(**{f"Mean {w}":df2['Number'].rolling(window=w).mean() for w in df1['Mean-1 input Value']})
          .groupby('Month')
          .sum())
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement