用 pandas 计算滚动平均值 [英] Calculating Rolling forward averages with pandas

查看:104
本文介绍了用 pandas 计算滚动平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算数据帧中的一些前滚平均值,但真的不知道从哪里开始.

I need to calculate some rolling forward averages in a dataframe and really don't know where to start.

我知道如果我想提前 10 天选择一个单元格,我会说我会做 df.shift(-10),但我想要做的是计算 10 到 15 之间的平均值提前几天说.

I know if I wanted to select a cell 10 days ahead say I would do df.shift(-10), but what I'm looking to do is calculate the average between 10 and 15 days ahead say.

所以我在想的是 df.rolling(-10,-15).mean(),如果我试图计算一个移动平均线 df.rolling(15, 10).mean() 可以完美地工作,我确实考虑过像这样计算平均值,然后以某种方式移动数据.

So what I'm kind of thinking is df.rolling(-10,-15).mean(), if I was trying to calculate just a moving average going backing in time df.rolling(15, 10).mean() would work perfectly and I did think about just calculating the averages like that, and then somehow shifting the data.

任何帮助都会很棒

非常感谢

推荐答案

您可以提前 5 天计算滚动平均值,然后 shift 10 个以上的周期.由于 rolling 是不允许的,你可以倒轴,向后计算,然后再倒转(见如何在前瞻性的基础上使用 Pandas 滚动_* 函数):

You could calculate the rolling mean 5 days ahead, and then shift that for 10 more periods. Since negative values in rolling are not allowed, you can invert the axis, calculate backwards, and then invert again (see How to use Pandas rolling_* functions on a forward-looking basis):

df = pd.DataFrame(np.random.rand(100, 2))
df[::-1].rolling(5).mean()[::-1].shift(-10)

这篇关于用 pandas 计算滚动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆