本文介绍了运行numpy数组值的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种快速的方法来保持numpy数组的运行最大值.例如,如果我的数组是:
I need a fast way to keep a running maximum of a numpy array. For example, if my array was:
x = numpy.array([11,12,13,20,19,18,17,18,23,21])
我想要:
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
但是我的数组有成千上万的条目,我需要多次调用它.似乎必须要有一个小技巧才能删除循环,但我似乎找不到任何有效的方法.替代方法是将此代码编写为C扩展名,但似乎我会重新发明轮子.
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.
推荐答案
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])
这篇关于运行numpy数组值的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!