0

I have tried to convert my array to a 2-D array and utilizing np.sort and np.lexsort but have not had any luck.

import numpy as np

# Here are the 2 arrays I would like to sort b using a.
a = np.array([6,5,3,4,1,2])
b = np.array(["x","y","z","a","b","c"])

Is it possible to sort b using a?

When printing b the output should be:

["b", "c", "z", "a", "y", "x"]
1
  • 1
    Have you looked at np.argsort? Commented Jul 20, 2019 at 18:34

1 Answer 1

1

You can use the built-in NumPy indexing:

In [1]: import numpy as np
   ...:
   ...: # Here are the 2 arrays I would like to sort b using a.
   ...: a = np.array([6,5,3,4,1,2])
   ...: b = np.array(["x","y","z","a","b","c"])

In [2]: b[a - 1]
Out[2]: array(['c', 'b', 'z', 'a', 'x', 'y'], dtype='<U1')

Also, I think your desired output is c, b, z, a, y, x instead of b, c, z, a, y, x.

Sign up to request clarification or add additional context in comments.

2 Comments

"Also, I think your desired output is c, b, z, a, y, x instead of b, c, z, a, y, x." - you probably think that because you're thinking of the operation "take element result[i] from the index of b given by a[i]", while the questioner is thinking of the dual operation "put b[i] in the cell of result given by a[i]", or the operation "take the permutation that would sort a and apply that permutation to b". Those operations would produce b, c, z, a, y, x.
Hey @tomothy32 thanks for the help. I did mean for it to be b, c, z, a, y, x. as that is the order if it were sorted by a. does that seem correct?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.