Numpy第一次出现的值大于现有值

use*_*827 125 python numpy

我有一个numpy的一维数组,我想找到一个值超过numpy数组中的值的索引的位置.

例如

aa = range(-10,10)
Run Code Online (Sandbox Code Playgroud)

找到位置,超出aa价值的位置5.

ask*_*han 166

这有点快(并且看起来更好)

np.argmax(aa>5)
Run Code Online (Sandbox Code Playgroud)

因为argmax将在第一个停止True("如果多次出现最大值,则返回与第一次出现相对应的索引.")并且不保存另一个列表.

In [2]: N = 10000

In [3]: aa = np.arange(-N,N)

In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop

In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop

In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是:如果输入数组中没有True值,np.argmax将很高兴地返回0(在这种情况下,这不是你想要的). (82认同)
  • 结果是正确的,但我觉得解释有点可疑.`argmax`似乎没有停在第一个'真'.(这可以通过在不同位置创建一个带有"True"的布尔数组来测试.)速度可能是由于`argmax`不需要创建输出列表这一事实. (6认同)
  • @DrV,我只是使用 NumPy 1.11.2 在 1000 万个元素的布尔数组上运行了 `argmax`,在不同位置有一个 `True`,而 `True` 的位置很重要。所以 1.11.2 的 `argmax` 似乎在布尔数组上“短路”。 (3认同)
  • 我认为你是对的,@DrV。我的解释是关于为什么它给出了正确的结果,尽管最初的意图实际上并不是寻求最大值,而不是为什么它更快,因为我不能声称理解“argmax”的内部细节。 (2认同)
  • 我用 2^30 个元素的数组重复了 @UlrichStern 的实验(用 1 预填充每个元素,然后用 0 预填充,然后添加一个真值以消除空白页欺骗、页错误噪声等)。当唯一的真实元素位于数组的开头而不是结尾时,np.argmax 的速度提高了 1e5 倍。这是 numpy 1.16.5 的情况。 (2认同)

小智 83

给定数组的排序内容,有一个更快的方法:searchsorted.

import time
N = 10000
aa = np.arange(-N,N)
%timeit np.searchsorted(aa, N/2)+1
%timeit np.argmax(aa>N/2)
%timeit np.where(aa>N/2)[0][0]
%timeit np.nonzero(aa>N/2)[0][0]

# Output
100000 loops, best of 3: 5.97 µs per loop
10000 loops, best of 3: 46.3 µs per loop
10000 loops, best of 3: 154 µs per loop
10000 loops, best of 3: 154 µs per loop
Run Code Online (Sandbox Code Playgroud)

  • 假设数组已排序(在问题中实际未指定),这确实是最佳答案.你可以使用`np.searchsorted(...,side ='right')`来避免笨拙的`+ 1` (15认同)
  • 我认为`side`参数只有在排序数组中有重复值时才会有所不同.它不会更改返回索引的含义,返回索引始终是您可以插入查询值的索引,将所有以下条目向右移动,并维护已排序的数组. (3认同)
  • @Gus,当相同的值同时存在于排序数组和插入数组中时,“side”会产生影响,无论其中任何一个中是否存在重复值。排序数组中的重复值只会夸大效果(两边的差异是插入的值在排序数组中出现的次数)。`side` *确实*改变了返回索引的含义,尽管它不会改变将值插入到这些索引处的排序数组中所产生的数组。一个微妙但重要的区别;事实上,如果“N/2”不在“aa”中,这个答案给出了错误的索引。 (2认同)

Moj*_*Moj 16

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16
Run Code Online (Sandbox Code Playgroud)


Nic*_*mer 16

我也对此感兴趣,并将所有建议的答案与perfplot进行了比较.(免责声明:我是perfplot的作者.)

如果您知道您正在查看的数组已经排序,那么

numpy.searchsorted(a, alpha)
Run Code Online (Sandbox Code Playgroud)

是给你的.这是一个固定时间操作,即,速度也不能依赖于数组的大小.你不可能比这更快.

如果您对阵列一无所知,那就不会出错

numpy.argmax(a > alpha)
Run Code Online (Sandbox Code Playgroud)

已经分类:

在此输入图像描述

未排序:

在此输入图像描述

重现情节的代码:

import numpy
import perfplot


alpha = 0.5

def argmax(data):
    return numpy.argmax(data > alpha)

def where(data):
    return numpy.where(data > alpha)[0][0]

def nonzero(data):
    return numpy.nonzero(data > alpha)[0][0]

def searchsorted(data):
    return numpy.searchsorted(data, alpha)

out = perfplot.show(
    # setup=numpy.random.rand,
    setup=lambda n: numpy.sort(numpy.random.rand(n)),
    kernels=[
        argmax, where,
        nonzero,
        searchsorted
        ],
    n_range=[2**k for k in range(2, 20)],
    logx=True,
    logy=True,
    xlabel='len(array)'
    )
Run Code Online (Sandbox Code Playgroud)

  • `np.searchsorted`不是恒定时间.它实际上是"O(log(n))".但是你的测试用例实际上是对`searchsorted`(即'O(1)`)的最佳情况进行基准测试. (4认同)

MSe*_*ert 6

元素之间步长恒定的数组

如果是range数组或任何其他线性增加的数组,则可以简单地以编程方式计算索引,而无需实际遍历数组:

def first_index_calculate_range_like(val, arr):
    if len(arr) == 0:
        raise ValueError('no value greater than {}'.format(val))
    elif len(arr) == 1:
        if arr[0] > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    first_value = arr[0]
    step = arr[1] - first_value
    # For linearly decreasing arrays or constant arrays we only need to check
    # the first element, because if that does not satisfy the condition
    # no other element will.
    if step <= 0:
        if first_value > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    calculated_position = (val - first_value) / step

    if calculated_position < 0:
        return 0
    elif calculated_position > len(arr) - 1:
        raise ValueError('no value greater than {}'.format(val))

    return int(calculated_position) + 1
Run Code Online (Sandbox Code Playgroud)

一个人可能可以改善这一点。我已经确保它可以正确地用于一些示例数组和值,但这并不意味着在那里不会有错误,特别是考虑到它使用浮点数...

>>> import numpy as np
>>> first_index_calculate_range_like(5, np.arange(-10, 10))
16
>>> np.arange(-10, 10)[16]  # double check
6

>>> first_index_calculate_range_like(4.8, np.arange(-10, 10))
15
Run Code Online (Sandbox Code Playgroud)

假设它无需任何迭代就可以计算位置,那么它将是恒定时间(O(1)),并且可能击败所有其他提到的方法。但是,它要求数组中的步长不变,否则将产生错误的结果。

使用numba的一般解决方案

更通用的方法是使用numba函数:

@nb.njit
def first_index_numba(val, arr):
    for idx in range(len(arr)):
        if arr[idx] > val:
            return idx
    return -1
Run Code Online (Sandbox Code Playgroud)

这将适用于任何数组,但必须迭代该数组,因此在一般情况下将是O(n)

>>> first_index_numba(4.8, np.arange(-10, 10))
15
>>> first_index_numba(5, np.arange(-10, 10))
16
Run Code Online (Sandbox Code Playgroud)

基准测试

尽管NicoSchlömer已经提供了一些基准,但我认为包括我的新解决方案并测试不同的“值”可能很有用。

测试设置:

import numpy as np
import math
import numba as nb

def first_index_using_argmax(val, arr):
    return np.argmax(arr > val)

def first_index_using_where(val, arr):
    return np.where(arr > val)[0][0]

def first_index_using_nonzero(val, arr):
    return np.nonzero(arr > val)[0][0]

def first_index_using_searchsorted(val, arr):
    return np.searchsorted(arr, val) + 1

def first_index_using_min(val, arr):
    return np.min(np.where(arr > val))

def first_index_calculate_range_like(val, arr):
    if len(arr) == 0:
        raise ValueError('empty array')
    elif len(arr) == 1:
        if arr[0] > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    first_value = arr[0]
    step = arr[1] - first_value
    if step <= 0:
        if first_value > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    calculated_position = (val - first_value) / step

    if calculated_position < 0:
        return 0
    elif calculated_position > len(arr) - 1:
        raise ValueError('no value greater than {}'.format(val))

    return int(calculated_position) + 1

@nb.njit
def first_index_numba(val, arr):
    for idx in range(len(arr)):
        if arr[idx] > val:
            return idx
    return -1

funcs = [
    first_index_using_argmax, 
    first_index_using_min, 
    first_index_using_nonzero,
    first_index_calculate_range_like, 
    first_index_numba, 
    first_index_using_searchsorted, 
    first_index_using_where
]

from simple_benchmark import benchmark, MultiArgument
Run Code Online (Sandbox Code Playgroud)

并使用以下方法生成图:

%matplotlib notebook
b.plot()
Run Code Online (Sandbox Code Playgroud)

项目在开始

b = benchmark(
    funcs,
    {2**i: MultiArgument([0, np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

numba函数执行最好,其次是calculate-function和searchsorted函数。其他解决方案的性能要差得多。

项目在末尾

b = benchmark(
    funcs,
    {2**i: MultiArgument([2**i-2, np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

对于较小的数组,numba函数的执行速度非常快,但是对于较大的数组,其计算功能和searchsorted函数的性能要好于后者。

项目在sqrt(len)

b = benchmark(
    funcs,
    {2**i: MultiArgument([np.sqrt(2**i), np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

这更有趣。numba和calculate函数再次表现出色,但是实际上触发了最糟糕的搜索排序情况,在这种情况下确实不能很好地工作。

没有值满足条件时的功能比较

另一个有趣的一点是,如果没有值应返回其索引,则这些函数的行为:

arr = np.ones(100)
value = 2

for func in funcs:
    print(func.__name__)
    try:
        print('-->', func(value, arr))
    except Exception as e:
        print('-->', e)
Run Code Online (Sandbox Code Playgroud)

结果如下:

first_index_using_argmax
--> 0
first_index_using_min
--> zero-size array to reduction operation minimum which has no identity
first_index_using_nonzero
--> index 0 is out of bounds for axis 0 with size 0
first_index_calculate_range_like
--> no value greater than 2
first_index_numba
--> -1
first_index_using_searchsorted
--> 101
first_index_using_where
--> index 0 is out of bounds for axis 0 with size 0
Run Code Online (Sandbox Code Playgroud)

Searchsorted,argmax和numba只会返回错误的值。但是searchsortednumba返回的索引不是该数组的有效索引。

功能whereminnonzerocalculate抛出一个异常。但是,只有例外calculate实际上可以说明任何帮助。

这意味着实际上必须将这些调用包装在一个适当的包装函数中,该包装函数可以捕获异常或无效的返回值并进行适当处理,至少在不确定该值是否可以在数组中的情况下。


注意:计算和searchsorted选项仅在特殊条件下起作用。“计算”功能需要一个恒定的步骤,而searchsorted需要对数组进行排序。因此,这些方法在适当的情况下可能很有用,但不是解决此问题的通用方法。如果要处理排序的 Python列表,则可能需要查看bisect模块,而不是使用Numpys searchsorted。


小智 6

我想提议

np.min(np.append(np.where(aa>5)[0],np.inf))
Run Code Online (Sandbox Code Playgroud)

这将返回满足条件的最小索引,如果条件不满足则返回无穷大(并where返回空数组)。