Home > Back-end >  Is it possible to do "rolling mean" first and then "groupby sum" in ONE GO?
Is it possible to do "rolling mean" first and then "groupby sum" in ONE GO?

Time:06-03

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()

CodePudding user response:

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())
  • Related