5

For example, to sort an array of complex numbers first by real part, then by magnitude of imaginary part, and then with negative imaginary parts first:

def order(a):
    return a.real, abs(a.imag), sign(a.imag)

z = array(sorted(z, key=order))

So

array([ 1.+2.j, 5.+0.j, 1.+0.j, 1.+1.j, 1.+1.j, 1.-1.j, 6.+0.j, 1.-1.j, 1.-2.j])

becomes

array([ 1.+0.j, 1.-1.j, 1.-1.j, 1.+1.j, 1.+1.j, 1.-2.j, 1.+2.j, 5.+0.j, 6.+0.j])

I think there's a way to do the same thing using numpy's argsort, which is probably faster, but I can't figure it out:

In [2]: argsort((a.real, abs(a.imag), sign(a.imag)))
Out[2]: 
array([[0, 2, 3, 4, 5, 7, 8, 1, 6],
       [1, 2, 6, 3, 4, 5, 7, 0, 8],
       [5, 7, 8, 1, 2, 6, 0, 3, 4]])

1 Answer 1

4

You can use np.lexsort :

import numpy as np
a = np.array([ 1.+2.j, 5.+0.j, 1.+0.j, 1.+1.j, 1.+1.j, 1.-1.j, 6.+0.j,
               1.-1.j, 1.-2.j])
sorted_idx = np.lexsort((np.sign(a.imag), np.abs(a.imag), a.real))
>>> a[sorted_idx]
array([ 1.+0.j,  1.-1.j,  1.-1.j,  1.+1.j,  1.+1.j,  1.-2.j,  1.+2.j,
        5.+0.j,  6.+0.j])

Notice that the sorting keys are in reversed ordered, i.e. last is principal.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.