在 Numpy/Python 中向量化迭代数组切片

Vectorizing iterative array slicing in Numpy/Python

我正在尝试矢量化一个 numpy 循环过程,在这个过程中我用每个循环迭代地切片数组:

for y in range(0, 10):
    maxpr[y] = npds[y*365:(y+1)*365].max(axis=0)

npds 是一个 (3650, 192, 288) numpy 数组,而 maxpr 是一个 (10,192,288) numpy 数组。

我正在有效地尝试摆脱这个通过矢量化迭代 yfor 循环。

我已经尝试过类似的方法:

years1 = np.arange(0,3650,365)
years2 = years1 + 365

maxpr = npds[years1:years2].argmax(axis=0)

但是这个returns错误“只能将整数标量数组转换为标量索引”。

如果您有任何建议,请告诉我;谢谢。

您可以将第一个维度分成 2 个维度,即将数组重新整形为 (10, 365, 192, 288),然后沿第二个轴 max

npds.reshape((10, 365, 192, 288)).max(axis=1)

示例

npds = np.arange(24).reshape((6,2,2))
maxpr = np.empty((3,2,2))

for y in range(0, 3):
    maxpr[y] = npds[y*2:(y+1)*2].max(axis=0)

(npds.reshape((3,2,2,2)).max(axis=1) == maxpr).all()
# True