首页 > 解决方案 > 以块的形式迭代一个 numpy 数组

问题描述

如何list_使用numpy.where()或 将数字排列成组numpy.select()。我想将数据分成 3 组,然后计算std()这些函数的标准偏差。所以程序将计算标准偏差457.334015,424.440002,394.795990的第一个值,424.440002,394.795990, 408.903992然后计算标准偏差等。它将继续这样下去,直到它到达list. 我希望在 457.334015,424.440002,394.795990计算第二个块之前删除第一个块424.440002,394.795990, 408.903992。我想从内存中删除块,所以我没有内存错误。这是否可以使用 numpy 并且不使用 for 循环。

number = 3
list_= np.array([457.334015,424.440002,394.795990,408.903992,398.821014,402.152008,435.790985,423.204987,411.574005,
404.424988,399.519989,377.181000,375.467010,386.944000,383.614990,375.071991,359.511993,328.865997,
320.510010,330.079010,336.187012,352.940002,365.026001,361.562012,362.299011,378.549011,390.414001,
400.869995,394.773010,382.556000])

标签: pythonfunctionnumpymemorynumpy-ndarray

解决方案


这篇文章

from numpy.lib.stride_tricks import as_strided
def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
list_= np.array([457.334015,424.440002,394.795990,408.903992,398.821014,402.152008,435.790985,423.204987,411.574005,
404.424988,399.519989,377.181000,375.467010,386.944000,383.614990,375.071991,359.511993,328.865997,
320.510010,330.079010,336.187012,352.940002,365.026001,361.562012,362.299011,378.549011,390.414001,
400.869995,394.773010,382.556000])
np.std(strided_app(list_, 3, 1), axis=1)

但是,此代码不会从数组中删除任何元素。另外,请记住,这里使用的函数带有来自 numpy 文档的警告!


推荐阅读