woodbine
woodbine

Reputation: 662

Sorting multiple numpy arrays

I have two numpy arrays in the same shape.

np.array_one = ([[1,4],[3,1]])
np.array_two = ([['A','B'],['C','D']])

I can sort multiple lists in python using zip, is there an equivalent for numpy arrays? So, I'd like to sort one list and then get the following list to sort in exactly the same way.

np.sort(array_one, array_two)

I'd like to produce the following equivalent:

array_one = ([[1,1],[3,4]])
array_two = ([['A','D'],['C','B']])

Upvotes: 1

Views: 1773

Answers (1)

akuiper
akuiper

Reputation: 215117

You can use numpy.argsort; apply argsort on array_one and get the index that sorts the array which can then be applied to array_two to sort it (in the sense of array_one):

array_one = np.array([[1,4],[3,1]])
array_two = np.array([['A','B'],['C','D']])

array_two.ravel()[array_one.argsort(axis=None).reshape(array_one.shape)]

#array([['A', 'D'],
#       ['C', 'B']], 
#      dtype='<U1')

Upvotes: 3

Related Questions