循环滚动均值 python

Loop rolling mean python

我正在尝试计算不同 window 尺寸的滚动平均值。

我有以下工作代码:

df['h1'] = (np.log1p(df['r1']) - np.log1p(df['r2'])) * 100

df['h3'] = df['h1'][beg_date:end_date].rolling(window=3).mean()
df['h6'] = df['h1'][beg_date:end_date].rolling(window=6).mean()
df['h12'] = df['h1'][beg_date:end_date].rolling(window=12).mean()

我想问下这段代码有没有更优雅的写法?也许在一个循环中。

任何提示都会有所帮助。

谢谢!

尝试:

for window in [3, 6, 12]:
    df[f"h{window}"] = df["h1"][beg_date:end_date].rolling(window=window).mean()
df['h1'] = (np.log1p(df['r1']) - np.log1p(df['r2'])) * 100
windows = [3,6,12] # put whatever you want
for my_window in windows:
    window_name = 'h'+str(my_window)
    df[window_name] = df['h1'][beg_date:end_date].rolling(window=my_window).mean()