[英]Running maximum of numpy array values
I need a fast way to keep a running maximum of a numpy array. 我需要一种快速的方法来保持运行最大的numpy数组。 For example, if my array was:
例如,如果我的数组是:
x = numpy.array([11,12,13,20,19,18,17,18,23,21])
I'd want: 我想要:
numpy.array([11,12,13,20,20,20,20,20,23,23])
Obviously I could do this with a little loop: 显然我可以做一个小循环:
def running_max(x):
result = [x[0]]
for val in x:
if val > result[-1]:
result.append(val)
else:
result.append(result[-1])
return result
But my arrays have hundreds of thousands of entries and I need to call this many times. 但是我的数组有成千上万的条目,我需要多次调用。 It seems like there's got to be a numpy trick to remove the loop, but I can't seem to find anything that will work.
似乎必须要有一个小技巧才能删除循环,但我似乎找不到任何有效的方法。 The alternative will be to write this as a C extension, but it seems like I'd be reinventing the wheel.
另一种方法是将其编写为C扩展,但似乎我会重新发明轮子。
numpy.maximum.accumulate
works for me. numpy.maximum.accumulate
对我numpy.maximum.accumulate
。
>>> import numpy
>>> numpy.maximum.accumulate(numpy.array([11,12,13,20,19,18,17,18,23,21]))
array([11, 12, 13, 20, 20, 20, 20, 20, 23, 23])
As suggested, there is scipy.maximum.accumulate
: 如建议的那样,有
scipy.maximum.accumulate
:
In [9]: x
Out[9]: [1, 3, 2, 5, 4]
In [10]: scipy.maximum.accumulate(x)
Out[10]: array([1, 3, 3, 5, 5])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.