gpt4 book ai didi

python - 在未排序的 numpy 数组中查找值列表的索引

转载 作者:行者123 更新时间:2023-12-01 03:27:48 26 4
gpt4 key购买 nike

我指的是一个类似的问题:Find indices of a list of values in a numpy array

在这种情况下,我们有一个已排序的主数组和另一个我们想要在主数组中找到索引的数组。

master = np.array([1,2,3,4,5])
search = np.array([4,2,2,3])

建议的解决方案是:
>>> master = np.array([1,2,3,4,5])
>>> search = np.array([4,2,2,3])
>>>np.searchsorted(master, search)
array([3, 1, 1, 2])

但是如果 master 没有被排序呢?
例如,如果我有两个这样的数组,其中第一个未排序:
>>>master = np.array([2,3,5,4,1])
>>>search = np.array([3,2,1,4,5])

我得到:
>>> np.searchsorted(master, search)
array([1, 0, 0, 2, 5])

但相反,我想:
array([1,0,4,3,2])

即 master 中搜索项的索引。

我如何使用 numpy 的 native 功能获得它们?(不使用 [np.where(master==i) for i in search])

谢谢

编辑:
在这种情况下,搜索数组是 master 的排列。然后我想找到如何排列 master 的索引以提供类似搜索的排列数组。

作为一般情况,搜索数组包含一些可能包含或不包含在 master 中的项目,例如:
>>>master = np.array([2,3,5,4,1])
>>>search = np.array([1,4,7])

最佳答案

免责声明:我为 an earlier revision of the question 写了这个答案.如果你想解决附录中的问题(当我们不只是寻找数组的排列时),see Will's answer .
如果所有其他方法都失败了,您需要暂时对主数组进行排序,然后在匹配元素后反转所需的排序顺序:

import numpy as np

master = np.array([2,3,5,4,1])
search = np.array([3,2,1,4,5])

# sorting permutation and its reverse
sorti = np.argsort(master)
sorti_inv = np.empty(sorti.shape,dtype=np.int64)
sorti_inv[sorti] = np.arange(sorti.size)

# get indices in sorted version
tmpind = np.searchsorted(master,search,sorter=sorti)

# transform indices back to original array with inverse permutation
final_inds = tmpind[sorti_inv]
上面的结果是正确的
array([1, 0, 4, 3, 2])

正如您在评论中指出的,您的特定 searchmaster是彼此的排列。在这种情况下,您可以交替对两个数组进行排序,并将逆排列与其他直接排列结合使用:
sorti = np.argsort(master)
sorti_inv = np.empty(sorti.shape,dtype=np.int64)
sorti_inv[sorti] = np.arange(sorti.size)
sorti_s = np.argsort(search)
final_inds = sorti_s[sorti_inv]
应该考虑搜索两个数组与在另一个数组的排序版本中搜索一个数组所需的工作量。我真的不知道哪个更快。

关于python - 在未排序的 numpy 数组中查找值列表的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40021914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com