做一个numpy的阵列单调没有一个Python循环 [英] Make a numpy array monotonic without a Python loop

查看:1209
本文介绍了做一个numpy的阵列单调没有一个Python循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该是单调值的一维数组(比方说减少),但也有随机的地区其中索引。值增加

我需要,其中每个区域被替换为一个值直接preceding它,使得所得数组进行排序的阵列

所以,如果给定的数组是:

  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])

我想要的结果是

  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])

下面是一个图形化的重新presentation:

我知道如何与一个Python循环来实现它,但是有一种用numpy的机器做到这一点?

Python的code为清楚:

  B = np.array(一)
因为我在范围内(1,b.size):
    若B [Ⅰ]≥ B〔I-1〕:
        B〔Ⅰ〕= b的[I-1]


解决方案

您可以使用 np.minimum.accumulate ,你通过移动阵列收集的最低值:

 >>> np.minimum.accumulate(一)
阵列([10,9.5,8,7.2,7.2,7.2,7,5,3,
         2.5,2.5,2])

目前阵列中的每个元素,此函数返回迄今所看到的最小值。

如果你想要一个数组是单调的增加,你可以使用 np.maximum.accumulate

在numpy的

许多其他通用功能有一个 积聚 的方法来模拟通过阵列循环,将所述函数应用于每个元素和收集返回的值成相同大小的阵列。

I have a 1D array of values which is supposed to be monotonic (let's say decreasing), but there are random regions where the value increases with index.

I need an array where each region is replaced with a value directly preceding it, so that the resulting array is sorted.

So if given array is:

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])

I want the result to be

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])

Here's a graphical representation:

I know how to achieve it with a Python loop, but is there a way to do this with NumPy machinery?

Python code for clarity:

b = np.array(a)
for i in range(1, b.size):
    if b[i] > b[i-1]:
        b[i] = b[i-1]

解决方案

You can use np.minimum.accumulate to collect the minimum values as you move through the array:

>>> np.minimum.accumulate(a)
array([ 10. ,   9.5,   8. ,   7.2,   7.2,   7.2,   7. ,   5. ,   3. ,
         2.5,   2.5,   2. ])

At each element in the array, this function returns the minimum value seen so far.

If you wanted an array to be monotonic increasing, you could use np.maximum.accumulate.

Many other universal functions in NumPy have an accumulate method to simulate looping through an array, applying the function to each element and collecting the returned values into an array of the same size.

这篇关于做一个numpy的阵列单调没有一个Python循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆