Lee
Lee

Reputation: 31070

Numpy "sort like" function

Say I have two arrays, v and w:

v=np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
w=np.random.random(10,)
array([ 0.20224634,  0.19145386,  0.44607429,  0.53601637,  0.29148741,
        0.62670435,  0.95371219,  0.63634805,  0.48733178,  0.17155278])

I can sort w like this:

np.sort(w)
array([ 0.17155278,  0.19145386,  0.20224634,  0.29148741,  0.44607429,
        0.48733178,  0.53601637,  0.62670435,  0.63634805,  0.95371219])

I would like to sort v in the same way as w. E.g. so that element 9 moves to element 0 and so on until v becomes:

array([9, 1, 0, 4, 2, 8, 3, 5, 7, 6])

Is there an easy way to do this that I'm missing?

If not, how would you do it?

Upvotes: 4

Views: 1043

Answers (1)

Davidmh
Davidmh

Reputation: 3865

You can get the order using np.argsort:

order = np.argsort(w)

And then just sort both arrays:

w = w[order]
v = v[order]

Upvotes: 8

Related Questions