为 pandas 滚动平均值制作自定义窗口类型 [英] Making a custom window type for pandas rolling mean

查看:129
本文介绍了为 pandas 滚动平均值制作自定义窗口类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道滚动允许您指定用于计算滚动平均值的窗口类型.文档列出了此处.但是,我正在尝试使用长度为4的对称加权窗口类型,其定义类似于(并且无法作为内置窗口使用):

I understand rolling allows you to specify the window type used for calculating the rolling mean. The docs list a variety of windows type options available here. However, I am trying to use a symmetrically weighted window type of length 4 whose definition is like (and is not available as built-in):

(a + 2*b + 2*c + d)/6

其中a,b,c和d是在任何给定时间的滚动窗口的四个元素,而[1/6、2/6、2/6、1/6]将是相关的权重.

where a,b,c and d are the four elements of the rolling window at any given time and [1/6, 2/6, 2/6, 1/6] would be the associated weights.

如果我使用默认的窗口类型(棚车),则会得到以下信息:

If I go by the default window type (boxcar), I get this:

import pandas as pd
rs = pd.Series(range(10))
print rs.rolling(4, win_type = 'boxcar').mean()

0    NaN
1    NaN
2    NaN
3    1.5
4    2.5
5    3.5
6    4.5
7    5.5
8    6.5
9    7.5
dtype: float64

您知道如何使用自定义的滚动窗口类型(在这种情况下为对称加权移动平均值)吗?

Any idea how I could go about using a custom defined rolling window type (a symmetrically weighted moving average, in this case)?

推荐答案

创建这样的内核:

import numpy as np
kernel = np.array([1,2,2,1])/6

然后与您的系列进行卷积:

then convolve with your series:

np.convolve(rs,kernel,'same')

这篇关于为 pandas 滚动平均值制作自定义窗口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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