gpt4 book ai didi

python - Pandas:在窗口数组上滚动平均值

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:32 27 4
gpt4 key购买 nike

类似于this answer ,我可以计算多个滚动平均值

d1 = df.set_index('DateTime').sort_index()
ma_1h = d1.groupby('Event').rolling('H').mean()
ma_2h = d1.groupby('Event').rolling('2H').mean()

但是如果我想对数组列表执行此操作,如何才能高效地执行此操作?

window_array = ['H','3H','6H','9H'] # etc

并且我的滚动平均值包含回我的原始数据框中

最佳答案

我相信您需要转换偏移量并通过列表理解在循环中创建新的DataFrame,最后concat :

from pandas.tseries.frequencies import to_offset

df1 = pd.concat([d1.groupby('Event').rolling(to_offset(x)).mean() for x in window_array],
axis=1,
keys=window_array)

示例:

rng = pd.date_range('2017-04-03', periods=10, freq='38T')
df = pd.DataFrame({'DateTime': rng, 'a': range(10), 'Event':[4] * 3 + [3] * 3 + [1] * 4})
print (df)


from pandas.tseries.frequencies import to_offset
window_array = ['H','3H','6H','9H']


d1 = df.set_index('DateTime').sort_index()
a = pd.concat([d1.groupby('Event')['a'].rolling(to_offset(x)).mean() for x in window_array],
axis=1,
keys=window_array)
print (a)
H 3H 6H 9H
Event DateTime
1 2017-04-03 03:48:00 6.0 6.0 6.0 6.0
2017-04-03 04:26:00 6.5 6.5 6.5 6.5
2017-04-03 05:04:00 7.5 7.0 7.0 7.0
2017-04-03 05:42:00 8.5 7.5 7.5 7.5
3 2017-04-03 01:54:00 3.0 3.0 3.0 3.0
2017-04-03 02:32:00 3.5 3.5 3.5 3.5
2017-04-03 03:10:00 4.5 4.0 4.0 4.0
4 2017-04-03 00:00:00 0.0 0.0 0.0 0.0
2017-04-03 00:38:00 0.5 0.5 0.5 0.5
2017-04-03 01:16:00 1.5 1.0 1.0 1.0

关于python - Pandas:在窗口数组上滚动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com