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”
JavaScript
x
4
1
for window1 in df1['Mean-1 input Value']:
2
df2[f"Mean {window1}"] = df2['Number'].rolling(window=window1).mean()
3
df3 = df2.groupby('Month').sum()
4
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.
JavaScript
1
7
1
for window1 in df1['Mean-1 input Value']:
2
df2[f"Mean {window1}"] = df2['Number'].rolling(window=window1).mean()
3
for window2 in df1['Mean-2 input Value']:
4
df2[f"Mean {window2}"] = df2['Number'].rolling(window=window2).mean()
5
6
df3 = df2.groupby('Month').sum()
7
Advertisement
Answer
I think yes, use:
JavaScript
1
4
1
df3 = (df2.assign(**{f"Mean {w}":df2['Number'].rolling(window=w).mean() for w in df1['Mean-1 input Value']})
2
.groupby('Month')
3
.sum())
4