[英]What is the most efficient way of finding the ranks of one numpy array in another?
Say I have two arrays:假设我有两个数组:
a = np.array([2, 5, 4, 3, 1])
b = np.array([4.5, 1.5, 3.5])
I want to find the rank of each element of a
if it were in b
.如果它在
b
中,我想找到a
的每个元素的等级。 So this would be the desired output:所以这将是所需的输出:
[1, 3, 2, 1, 0]
The following code technically works for small arrays but is extremely slow if a
and b
are 10,000+ in size:以下代码在技术上适用于小型数组,但如果
a
和b
的大小为 10,000+,则速度非常慢:
ranks = [rankdata(b + [i])[-1] - 1 for i in a]
What is the most efficient way of achieving this result?实现这一结果的最有效方法是什么?
Use searchsorted
使用
searchsorted
ind = np.argsort(y)
np.searchsorted(y, x, sorter=ind)
# array([1, 3, 2, 1, 0], dtype=int64)
If y
has duplicates, you may have to tinker with the side
argument.如果
y
有重复项,您可能需要修改side
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.