Lev*_*sky 17 python arrays numpy vectorization
我有一个数组的值,它应该是单调的(比如减少),但是随机区域的值随着索引而增加.
我需要一个数组,其中每个区域都替换为它前面的值,以便对结果数组进行排序.
所以如果给定的数组是:
a = np.array([10.0, 9.5, 8.0, 7.2, 7.8, 8.0, 7.0, 5.0, 3.0, 2.5, 3.0, 2.0])
Run Code Online (Sandbox Code Playgroud)
我想要结果
b = np.array([10.0, 9.5, 8.0, 7.2, 7.2, 7.2, 7.0, 5.0, 3.0, 2.5, 2.5, 2.0])
Run Code Online (Sandbox Code Playgroud)
这是一个图形表示:

我知道如何用Python循环实现它,但有没有办法用NumPy机器来做到这一点?
Python代码为清晰起见:
b = np.array(a)
for i in range(1, b.size):
if b[i] > b[i-1]:
b[i] = b[i-1]
Run Code Online (Sandbox Code Playgroud)
Ale*_*ley 20
np.minimum.accumulate在数组中移动时,您可以使用它来收集最小值:
>>> np.minimum.accumulate(a)
array([ 10. , 9.5, 8. , 7.2, 7.2, 7.2, 7. , 5. , 3. ,
2.5, 2.5, 2. ])
Run Code Online (Sandbox Code Playgroud)
在数组中的每个元素处,此函数返回到目前为止看到的最小值.
如果你想要一个单调增加的数组,你可以使用np.maximum.accumulate.
NumPy中的许多其他通用函数都有一种accumulate方法来模拟循环数组,将函数应用于每个元素并将返回的值收集到相同大小的数组中.