在没有Python循环的情况下制作一个numpy数组单调

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方法来模拟循环数组,将函数应用于每个元素并将返回的值收集到相同大小的数组中.

  • 哇。我不知道“.accumulate”!这与 Python2 `reduce` (或 Python3 `functools.reduce`)非常接近,我对吗? (2认同)
  • 它非常相似 - `accumulate` 存储每个元素的操作结果,返回相同长度的数组,而 unfunc 的 [`reduce`](http://docs.scipy.org/doc/numpy/reference/ generated /numpy.ufunc.reduce.html) 方法仅显示最终结果(折叠数组)。 (2认同)