如何找到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:
我已经为几种方法建立了基准:
argwhere
nonzero
如问题所述.tostring()
如@Rob Reilink的回答可以使用Python和Fortran代码。我跳过了那些没有希望的,比如转换成一个列表。
对数刻度的结果。X轴是指针的位置(如果它在数组的下面,则需要更长的时间才能找到);最后一个值是不在数组中的指针。Y轴是找到它的时间。
这个数组有100万个元素,测试运行了100次。结果仍然有点波动,但定性趋势很明显:Python和f2py在第一个元素退出,因此它们的比例不同。如果指针不在前1%,Python会变得太慢,而
f2py
则很快(但您需要编译它)。总而言之,f2py是最快的解决方案,尤其是在针出现得相当早的情况下。
它不是内置的,但它真的只是2分钟的工作。将this添加到名为
search.f90
的文件中:如果您要查找的不是
integer
,只需更改类型。然后使用以下命令编译:之后您可以(从Python)执行以下操作:
此功能请求计划用于Numpy 2.0.0:https://github.com/numpy/numpy/issues/2269
虽然对你来说已经太晚了,但是为了将来的参考: 在numpy实现之前,使用numba(1)是最简单的方法。如果使用anaconda python发行版,则应该已经安装了它。 这段代码将被编译,因此速度很快。
然后:
相关问题 更多 >
编程相关推荐