2

I am trying to do the following:

import numpy as np
A = np.array([1,5,2,7,1])
B = np.sort(A)
print B
>>> [1,1,2,5,7]

I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that

print C
>>[0,4,2,1,3]

which refers to 1 in B being present in A at 0 and 4th location, 5 in B was present in A at 1st location, etc.

I tried using np.where( B == A) but it produces gibberish

3 Answers 3

9
import numpy as np
A = np.array([1,5,2,7,1])
print np.argsort(A) #prints [0 4 2 1 3]
Sign up to request clarification or add additional context in comments.

Comments

3

If you don't want to imporr numpy for any reason you can also use this code:

a = [1,5,2,7,1]
b = zip(a, range(len(a)))
tmp = sorted(b, key=lambda x: x[0])
c = map( lambda x: x[1], tmp)
print c

[0, 4, 2, 1, 3]

Comments

1

https://repl.it/CVbI

A = [1,5,2,7,1]
for i,e in sorted(enumerate(A), key=lambda x: x[1]):
  print(i, e)

B = [x for x,_ in sorted(enumerate(A), key=lambda x: x[1])]
A = sorted(A)

print(A)
print(B)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.