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]])