如何在 pandas 中使用自定义权重计算滚动平均值? [英] How do I calculate a rolling mean with custom weights in pandas?

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

问题描述

Pandas 文档 http://pandas.pydata.org/pandas-docs/stable/computation.html 有一个如何计算移动平均线的例子:

The Pandas documentation http://pandas.pydata.org/pandas-docs/stable/computation.html has an example of how to calculate moving averages:

ser = pd.Series(np.random.randn(10), index=pd.date_range('1/1/2000', periods=10))
pd.rolling_window(ser, 5, 'boxcar')

第二行计算一个滚动平均值,窗口为 5,五个观测值中的每一个都具有相同的权重.文档引人入胜地提到了使用自定义权重的可能性(当传递 win_type 而不是明确指定权重时......"),但你怎么做?

The second line calculates a rolling average with a window of 5 and equal weights on each of the five observations. The docs refer tantalizingly to the possibility of using custom weights ("When passing a win_type instead of explicitly specifying the weights..."), but how do you do it?

谢谢!

推荐答案

我不是数学专家,但 stahlous 解释你需要什么 此处.

I'm not Math expert, but stahlous explain what you need here.

我试着测试一下:

import pandas as pd

ser = pd.Series([1,1,1], index=pd.date_range('1/1/2000', periods=3))
print ser

rm1 = pd.rolling_window(ser, window=[2,2,2], mean=False)
rm2 = pd.rolling_window(ser, window=[2,2,2]) #, mean=True

print rm1
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     6
#Freq: D, dtype: float64
print rm2
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     1
#Freq: D, dtype: float64

我将 window 设置为 ndarray ([2,2,2]) 并计算加权和 (rm1>) 和加权平均值 (rm2).

I setting window to ndarray ([2,2,2]) and calculated weighted sum (rm1) and weighted mean (rm2).

pandas.rolling_window:

window:int 或 ndarray:
加权窗口规范.如果窗口是整数,则将其视为窗口长度,并且需要 win_type

window : int or ndarray:
Weighting window specification. If the window is an integer, then it is treated as the window length and win_type is required

mean:布尔值,默认为 True
如果 True 计算加权平均值,否则加权总和

mean : boolean, default True
If True computes weighted mean, else weighted sum

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

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