Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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
pythonnwise numpy数组迭代_Python_Numpy - Fatal编程技术网

pythonnwise numpy数组迭代

pythonnwise numpy数组迭代,python,numpy,Python,Numpy,是否有一个numpy函数可以有效地允许迭代 # http://seriously.dontusethiscode.com/2013/04/28/nwise.html from itertools import tee, islice nwise = lambda xs, n=2: zip(*(islice(xs, idx, None) for idx, xs in enumerate(tee(xs, n)))) 将平均数应用于元素nwise?要获得移动平均线?通用: import numpy

是否有一个numpy函数可以有效地允许迭代

# http://seriously.dontusethiscode.com/2013/04/28/nwise.html
from itertools import tee, islice
nwise = lambda xs, n=2: zip(*(islice(xs, idx, None) for idx, xs in enumerate(tee(xs, n))))
将平均数应用于元素nwise?要获得移动平均线?

通用:

import numpy as np
from numpy.lib.stride_tricks import as_strided

def moving_slice(a, k):
    a = a.ravel()
    return as_strided(a, (a.size - k + 1, k), 2 * a.strides)
移动平均值更好:

def moving_avg(a, k):
    ps = np.cumsum(a)
    return (ps[k-1:] - np.r_[0, ps[:-k]]) / k
例如:

a = np.arange(10)

moving_avg(a, 4)
# array([ 1.5,  2.5,  3.5,  4.5,  5.5,  6.5,  7.5])

ms = moving_slice(a, 4)
ms
# array([[0, 1, 2, 3],
#        [1, 2, 3, 4],
#        [2, 3, 4, 5],
#        [3, 4, 5, 6],
#        [4, 5, 6, 7],
#        [5, 6, 7, 8],
#        [6, 7, 8, 9]])

# no data are copied:
a[4] = 0
ms
# array([[0, 1, 2, 3],
#        [1, 2, 3, 0],
#        [2, 3, 0, 5],
#        [3, 0, 5, 6],
#        [0, 5, 6, 7],
#        [5, 6, 7, 8],
#        [6, 7, 8, 9]])

很好,请给我一点时间,让我看看这些…:)非常感谢你的回答!它非常聪明