I have 2 1D numpy arrays of the same dimension, a
and b
, and I want to sort
the arrays using the values in b
. This can be achieved with lists as outlined
in this previous post or by using numpy’s argsort.
First we make some example data
import numpy as np
a = np.array(range(99,109))
b = np.array(np.arange(500,1000,50))
np.random.shuffle(b)
So our data looks like:
>>> print a
[ 99 100 101 102 103 104 105 106 107 108]
>>> print b
[ 700 550 650 800 750 500 950 600 850 900]
We can then use argsort
on b
to get the indexes of b
if it was sorted:
indexes = b.argsort()
>>> print indexes
[5 1 7 2 0 4 3 8 9 6]
And then apply these indexes to our original data to reorder it:
a = a[indexes]
b = b[indexes]
Which yields:
>>> print a
[104 100 106 101 99 103 102 107 108 105]
>>> print b
[ 500 550 600 650 700 750 800 850 900 950]