Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要前六个观测值才能在python wma滚动平均值中正确计算_Python_Moving Average - Fatal编程技术网

需要前六个观测值才能在python wma滚动平均值中正确计算

需要前六个观测值才能在python wma滚动平均值中正确计算,python,moving-average,Python,Moving Average,我正在尝试计算熊猫数据帧中所有时间序列值的加权移动平均值,窗口大小为7。出于某种原因,它在前6次观测中返回NaN,从第7次观测开始,它返回的是正确的值。虽然第7个值是正确的,但我的方法肯定有问题。对如何纠正有什么建议或想法?提前谢谢你 df=pd.DataFrame(data) def calc_wma(df, wd_size, weights=1): """ Takes in a series and calculates the WMA wit

我正在尝试计算熊猫数据帧中所有时间序列值的加权移动平均值,窗口大小为7。出于某种原因,它在前6次观测中返回NaN,从第7次观测开始,它返回的是正确的值。虽然第7个值是正确的,但我的方法肯定有问题。对如何纠正有什么建议或想法?提前谢谢你

df=pd.DataFrame(data)

def calc_wma(df, wd_size, weights=1):
    """
    Takes in a series and calculates the WMA with a window size of wd_size
    """
    wma = None
    if isinstance(weights, int):
        weights = np.full(wd_size, weights)

    assert len(weights) == wd_size, "Q4: The size of the weights must be the same as the window size. "

    weights = np.arange(1, wd_size + 1)
    wma=df.rolling(7).apply(lambda cases: np.dot(cases, weights)/weights.sum(), raw=True)
    return wma


calc_wma(df,7)



Out: 
2020-01-23  NaN
2020-01-24  NaN
2020-01-25  NaN
2020-01-26  NaN
2020-01-27  NaN
2020-01-28  NaN
2020-01-29  1034.107143
2020-01-30  1350.714286
2020-01-31  1503.250000
2020-02-01  1710.071429
2020-02-02  2518.607143
2020-02-03  2769.714286
2020-02-04  3166.750000
2020-02-05  3448.714286

您无法计算样本前6天的7天移动平均值,这就是为什么输出的前6天缺少值。

谢谢您,Pablo。你说的话确实有道理。我还需要前六天的平均值。因此,我想我必须重新构造我的函数,以找出如何通过为每个函数应用正确的滚动窗口来循环。如果有人对如何做到这一点有任何想法,我愿意接受建议。谢谢