scipy Numpy数组:高效查找匹配索引

p1iqtdky  于 2023-05-07  发布在  其他
关注(0)|答案(3)|浏览(189)

我有两个列表,其中一个是巨大的(数百万个元素),另一个是几千个。我想做以下事情

bigArray=[0,1,0,2,3,2,,.....]

smallArray=[0,1,2,3,4]

for i in len(smallArray):
  pts=np.where(bigArray==smallArray[i])
  #Do stuff with pts...

上面的工作,但很慢。有没有什么方法可以更有效地做到这一点,而不必求助于用C编写的东西?

bvjveswy

bvjveswy1#

Numpy提供了numpy.searchsorted函数:http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.searchsorted.html
示例:

>>> import numpy as np
>>> sorted = np.argsort(big_list)
>>> r = np.searchsorted(big_list, small_list, side='right',sorter=sorted)
>>> l  = np.searchsorted(big_list, small_list, side='left',sorter=sorted)
>>> for b, e in zip(l, r):
...     inds = sorted[b:e]
wfauudbj

wfauudbj2#

在您的情况下,您可能会受益于预排序您的大数组。下面的例子演示了如何将时间从~ 45秒减少到2秒(在我的笔记本电脑上)(对于一组特定长度的数组5e 6和1 e3)。显然,如果数组大小相差很大,那么这个解决方案就不是最优的。例如,默认解决方案的复杂度为O(bigN*smallN),但对于我建议的解决方案,复杂度为O((bigN+smallN)*log(bigN))

import numpy as np, numpy.random as nprand, time, bisect

bigN = 5e6
smallN = 1000
maxn = 1e7
nprand.seed(1)  
bigArr = nprand.randint(0, maxn, size=bigN)
smallArr = nprand.randint(0, maxn, size=smallN)

# brute force 
t1 = time.time()
for i in range(len(smallArr)):
    inds = np.where(bigArr == smallArr[i])[0]
t2 = time.time()
print "Brute", t2-t1

# not brute force (like nested loop with index scan)
t1 = time.time()
sortedind = np.argsort(bigArr)
sortedbigArr = bigArr[sortedind]
for i in range(len(smallArr)):
    i1 = bisect.bisect_left(sortedbigArr, smallArr[i])
    i2 = bisect.bisect_right(sortedbigArr, smallArr[i])
    inds = sortedind[i1:i2]
t2=time.time()
print "Non-brute", t2-t1

输出:
电话:+86-527 - 8530121
非暴力1.57193303108

bejyjqdl

bejyjqdl3#

到目前为止,我看不出有任何需要numpy;你可以使用defaultdict,只要你的内存足够,如果观察的数量不是太多,应该是数百万。

big_list = [0,1,0,2,3,2,5,6,7,5,6,4,5,3,4,3,5,6,5]
small_list = [0,1,2,3,4]

from collections import defaultdict

dicto = defaultdict(list) #dictionary stores all the relevant coordinates
                          #so you don't have to search for them later

for ind, ele in enumerate(big_list):
    dicto[ele].append(ind)

结果:

>>> for ele in small_list:
...     print dicto[ele]
... 
[0, 2]
[1]
[3, 5]
[4, 13, 15]
[11, 14]

这应该能给予你一些速度。

相关问题