每第 n 个实例在 Numpy 数组中查找最大值

Finding the maximum in a Numpy array every nth instance

我有一个每秒都有风速和风向的大文件。我已将每个元素存储到一个 numpy 数组中。例如,风速是 ws=(7, 8, 8.5, 8, 9.5)。我想用最大 1 分钟风速填充另一个数组,所以每 60 个实例,我需要拉最大。我试过这个:

gust = np.full(len(ws), 0) 
indices = sig.argrelmax(ws)
gust[indices] = ws[indices]

他任意提取最大值并将它们成功输入数组,同时保持它们在 ws 数组中的相同索引,但是 1) 我需要它来检查 60 个批次中的最大值(1-60、61- 120,...等)。 2)它将数字变成一个整数,我需要浮点数保持为浮点数。

如果元素个数是60的倍数,可以reshape数组,然后计算第二个维度上的最大值:

ws.reshape(-1, 60).max(axis=1)

如果我们使用随机数据,我们得到:

>>> ws = np.random.randn(7*60)
>>> ws.reshape(-1, 60).max(axis=1)
array([2.81337727, 2.30824229, 2.31009178, 2.5588816 , 3.41887582,
       2.21686554, 2.10892784])

如果测量次数不是60的倍数,可以用零“填充”(因为风速最小为0):

# padding zeros at the end
ws2 = np.append(ws, (0,) * ((60-len(ws))%60))
ws2.reshape(-1, 60).max(axis=1)

如果你想以更直接的方式处理非 60 的倍数,你可以使用 reduceat:

wind=np.random.normal(size=1000)
res=np.maximum.reduceat(wind, np.r_[:wind.size:60])

np.r_ 创建索引数组 0,60,120...

reduceat 在连续索引

之间的切片处执行 ufunc maximum

因此 res 的最后一个元素是 wind

最后 1000%60 个元素的最大值