RNdev
RNdev

Reputation: 1251

Python: how to make indices of second array match indices of first array when first array gets sorted?

I have two Numpy arrays: a: [2,5,3,7,9,1] and b: [1,2,3,4,5,6]. I want to sort a, and have the elements of b shift in the same way that the indices of a do. In this case, a would become [1,2,3,5,7,9] and b would become [6,1,3,2,4,5]. I know how to use np.sort to sort a, but how would I re-arrange b?

Upvotes: 0

Views: 56

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27609

With NumPy's argsort:

>>> b[a.argsort()]
array([6, 1, 3, 2, 4, 5])

An alternative without NumPy:

>>> a, b = zip(*sorted(zip(a, b)))
>>> a
(1, 2, 3, 5, 7, 9)
>>> b
(6, 1, 3, 2, 4, 5)

Upvotes: 2

Related Questions