我需要找到一个数组中第一个小于或等于元素在另一个数组中出现的索引。一种可行的方法是:
import numpy
a = numpy.array([10,7,2,0])
b = numpy.array([10,9,8,7,6,5,4,3,2,1])
indices = [numpy.where(a<=x)[0][0] for x in b]
indices 的值为 [0, 1, 1, 1, 2, 2, 2, 2, 2, 3],这正是我所需要的。当然,问题是 python“for”循环很慢,我的数组可能有数百万个元素。这有什么 NumPy 的技巧吗?这不起作用,因为它们的数组长度不同:
indices = numpy.where(a<=b) #XXX: raises an exception
谢谢!
最佳答案
这可能是一个特例,但你应该可以使用 numpy digitize .这里需要注意的是,bin 必须单调递减或递增。
>>> import numpy
>>> a = numpy.array([10,7,2,0])
>>> b = numpy.array([10,9,8,7,6,5,4,3,2,1])
>>> indices = [numpy.where(a<=x)[0][0] for x in b]
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3]
>>> numpy.digitize(b,a)
array([0, 1, 1, 1, 2, 2, 2, 2, 2, 3])
计时测试设置:
a = np.arange(50)[::-1]
b = np.random.randint(0,50,1E3)
np.allclose([np.where(a<=x)[0][0] for x in b],np.digitize(b,a))
Out[55]: True
一些时间:
%timeit [np.where(a<=x)[0][0] for x in b]
100 loops, best of 3: 4.97 ms per loop
%timeit np.digitize(b,a)
10000 loops, best of 3: 48.1 µs per loop
看起来速度提高了两个数量级,但这在很大程度上取决于 bin 的数量。您的时间会有所不同。
为了与 Jamie 的回答进行比较,我对以下两段代码进行了计时。因为我主要想关注 searchsorted
与 digitize
的速度,所以我稍微削减了 Jamie 的代码。相关 block 在这里:
a = np.arange(size_a)[::-1]
b = np.random.randint(0, size_a, size_b)
ja = np.take(a, np.searchsorted(a, b, side='right', sorter=a)-1)
#Compare to digitize
if ~np.allclose(ja,np.digitize(b,a)):
print 'Comparison failed'
timing_digitize[num_a,num_b] = timeit.timeit('np.digitize(b,a)',
'import numpy as np; from __main__ import a, b',
number=3)
timing_searchsorted[num_a,num_b] = timeit.timeit('np.take(a, np.searchsorted(a, b, side="right", sorter=a)-1)',
'import numpy as np; from __main__ import a, b',
number=3)
这有点超出了我有限的 matplotlib 能力,所以这是在 DataGraph 中完成的。我绘制了 timing_digitize/timing_searchsorted
的对数比,因此大于零的值 searchsorted
更快,小于零的值 digitize
更快。颜色也给出了相对速度。例如显示在右上角 (a = 1E6, b=1E6) digitize
比 searchsorted
慢 300 倍,而对于较小的尺寸 digitize
最多可以快 10 倍。黑线大致是收支平衡点:
看起来对于原始速度 searchsorted
对于大的情况几乎总是更快,但是如果 bin 的数量很少,digitize
的简单语法几乎一样好。
关于python - 比较两个不同长度的numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875970/