0

idtopick是一个 id 数组

     idtopick=array([50,48,12,125,3458,155,299,6,7,84,58,63,0,8,-1])

idtolook是另一个包含我感兴趣的 id 的数组

     idtolook=array([0,8,12,50])

我想将idtopick对应的位置存储在另一个数组中idtolook

这是我的解决方案

    positions=array([where(idtopick==dummy)[0][0] for dummy in idtolook])

导致

    array([12, 13,  2,  0])

它有效,但实际上我正在使用的数组存储数百万个点,因此上述脚本相当慢。我想知道是否有办法让它更快。另外,我想保持顺序,idtolook因此任何可以对其进行排序的算法都不适用于我的情况。

4

1 回答 1

3

您可以使用排序:

 sorter = np.argsort(idtopick, kind='mergesort') # you need stable sorting
 sorted_ids = idtopick[sorter]
 positions = np.searchsorted(sorted_ids, idtolook)
 positions = sorter[positions]

请注意,尽管idtolook. idtopick您实际上也可以将 idtolook 排序到结果数组中,这应该更快:

 c = np.concatenate((idtopick, idtolook))
 sorter = np.argsort(c, kind='mergesort')
 #reverse = np.argsort(sorter) # The next two lines are this, but faster:
 reverse = np.empty_like(sorter)
 reverse[sorter] = np.arange(len(sorter))
 positions = sorter[reverse[-len(idtolook):]-1]

这与集合操作有相似之处。

于 2012-10-19T09:50:13.700 回答