查找排序数组中元素的位置 [英] Find positions of elements in sorted array

查看:53
本文介绍了查找排序数组中元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些想要按降序排序的 numpy 数组(所有元素都是唯一的).我需要找出初始数组的元素将在排序数组中的哪些位置.

Suppose I have some numpy array (all elements are unique) that I want to sort in descending order. I need to find out which positions elements of initial array will take in sorted array.

示例.

In1: [1, 2, 3] # Input

Out1: [2, 1, 0] # Expected output

In2: [1, -2, 2] # Input

Out2: [1, 2, 0] # Expected output

我试过这个:

def find_positions(A):
    A = np.array(A)
    A_sorted = np.sort(A)[::-1]
    return np.argwhere(A[:, None] == A_sorted[None, :])[:, 1]

但是当输入数组非常大(len > 100000)时它不起作用.我做错了什么,我该如何解决?

But it doesn't work when the input array is very large (len > 100000). What I did wrong and how can I resolve it?

推荐答案

方法 #1

我们可以使用双 argsort -

We could use double argsort -

np.argsort(a)[::-1].argsort() # a is input array/list

方法#2

我们可以使用一个 argsort 然后使用数组赋值 -

We could use one argsort and then array-assignment -

# https://stackoverflow.com/a/41242285/ @Andras Deak
def argsort_unique(idx):
    n = idx.size
    sidx = np.empty(n,dtype=int)
    sidx[idx] = np.arange(n)
    return sidx

out = argsort_unique(np.argsort(a)[::-1])

这篇关于查找排序数组中元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆