如何摆脱 python for 循环? t 通常不是均匀间隔的(仅在简单的示例中)。使用 pandas 的解决方案也很好。
import numpy as np
n = 100
t = np.arange(n)
y = np.arange(n)
edges = np.array([2., 5.5, 19, 30, 50, 72, 98])
indices = np.searchsorted(t, edges)
maxes = np.zeros(len(edges)-1)
for i in range(len(edges)-1):
maxes[i] = np.max(y[indices[i]:indices[i+1]])
print(maxes)
更新: 我认为reduceat可能会这样做,但我不明白语法。
最佳答案
reduceat 很好地完成了这项工作。 30 分钟前我还不知道该功能。
maxes = np.maximum.reduceat(y, indices)[:-1]
关于python - numpy 对数组段上的最大值进行向量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38920043/