If I have two parallel lists and want to sort them by the order of the elements in the first, it’s very easy:
>>> a = [2, 3, 1]
>>> b = [4, 6, 7]
>>> a, b = zip(*sorted(zip(a,b)))
>>> print a
(1, 2, 3)
>>> print b
(7, 4, 6)
How can I do the same using numpy arrays without unpacking them into conventional Python lists?
b[a.argsort()]should do the trick.Here’s how it works. First you need to find a permutation that sorts a.
argsortis a method that computes this:You can easily check that this is right:
Now apply the same permutation to b.