Numpy:查找值fas的第一个索引

2024-09-24 22:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到Numpy数组中第一个数字的索引? 速度对我很重要。我对以下答案不感兴趣,因为它们会扫描整个数组,并且在找到第一个匹配项时不会停止:

itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]

注1:该问题的任何答案似乎都不相关Is there a Numpy function to return the first index of something in an array?

注2:使用C编译的方法比使用Python循环更好。


Tags: 答案numpyisfunction数字数组itemwhere
3条回答

我已经为几种方法建立了基准:

  • argwhere
  • nonzero如问题所述
  • .tostring()如@Rob Reilink的回答
  • python循环
  • Fortran循环

可以使用PythonFortran代码。我跳过了那些没有希望的,比如转换成一个列表。

对数刻度的结果。X轴是指针的位置(如果它在数组的下面,则需要更长的时间才能找到);最后一个值是不在数组中的指针。Y轴是找到它的时间。

benchmark results

这个数组有100万个元素,测试运行了100次。结果仍然有点波动,但定性趋势很明显:Python和f2py在第一个元素退出,因此它们的比例不同。如果指针不在前1%,Python会变得太慢,而f2py则很快(但您需要编译它)。

总而言之,f2py是最快的解决方案,尤其是在针出现得相当早的情况下。

它不是内置的,但它真的只是2分钟的工作。将this添加到名为search.f90的文件中:

subroutine find_first(needle, haystack, haystack_length, index)
    implicit none
    integer, intent(in) :: needle
    integer, intent(in) :: haystack_length
    integer, intent(in), dimension(haystack_length) :: haystack
!f2py intent(inplace) haystack
    integer, intent(out) :: index
    integer :: k
    index = -1
    do k = 1, haystack_length
        if (haystack(k)==needle) then
            index = k - 1
            exit
        endif
    enddo
end

如果您要查找的不是integer,只需更改类型。然后使用以下命令编译:

f2py -c -m search search.f90

之后您可以(从Python)执行以下操作:

import search
print(search.find_first.__doc__)
a = search.find_first(your_int_needle, your_int_array)

此功能请求计划用于Numpy 2.0.0:https://github.com/numpy/numpy/issues/2269

虽然对你来说已经太晚了,但是为了将来的参考: 在numpy实现之前,使用numba(1)是最简单的方法。如果使用anaconda python发行版,则应该已经安装了它。 这段代码将被编译,因此速度很快。

@jit(nopython=True)
def find_first(item, vec):
    """return the index of the first occurence of item in vec"""
    for i in xrange(len(vec)):
        if item == vec[i]:
            return i
    return -1

然后:

>>> a = array([1,7,8,32])
>>> find_first(8,a)
2

相关问题 更多 >