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"]
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
in0
  • 57
  • 1
  • 2
  • 5

1 Answers1

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.

iz_
  • 15,923
  • 3
  • 25
  • 40
  • 1
    "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`. – user2357112 Jul 20 '19 at 18:13
  • 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? – in0 Jul 20 '19 at 18:21