Home > database >  Any efficient analogue of argsort for array of indices with NumPy?
Any efficient analogue of argsort for array of indices with NumPy?

Time:05-07

I have an array of indices like a = [2, 4, 1, 0, 3] and I want to transform it into np.argsort(a) = [3, 2, 0, 4, 1]. The problem is that argsort has O(n*log(n)) timing, but for my case it may be O(n) and I even have code for this:

b = np.zeros(a.size)
for i in range(a.size):
    b[a[i]] = i

The second problem is that cycles are slow in Python and I hope that it's possible to use some NumPy tricks to achieve the goal.

CodePudding user response:

Do you have all numbers for 0 to len(a)-1?

Then use smart indexing:

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

b = np.empty(len(a), dtype=int) # or b = np.empty_like(a)
b[a] = np.arange(len(a))
b

output: array([3, 2, 0, 4, 1])

  • Related