Sort NumPy float array column by column Sort NumPy float array column by column numpy numpy

Sort NumPy float array column by column


numpy.lexsort will work here:

A[np.lexsort(A.T)]

You need to transpose A before passing it to lexsort because when passed a 2d array it expects to sort by rows (last row, second last row, etc).

The alternative possibly slightly clearer way is to pass the columns explicitly:

A[np.lexsort((A[:, 0], A[:, 1]))]

You still need to remember that lexsort sorts by the last key first (there's probably some good reason for this; it's the same as performing a stable sort on successive keys).


the following will work, but there might be a faster way:

A = np.array(sorted(A,key=tuple))


Just replace the whole thing (including the unique part with) for A being 2D:

A = np.ascontiguousarray(A) # just to make sure...A = A.view([('', A.dtype)] * A.shape[1])A = np.unique(A)# And if you want the old view:A = A.view(A.dtype[0]).reshape(-1,len(A.dtype))

I hope you are not using the set solution from the linked question unless you do not care too much about speed. The lexsort etc. is in generally great, but here not necessary since the default sort will do (if its a recarray)


Edit: A different view (with much the same result), but a bit more elegent maybe as no reshape is needed:

A = A.view([('', A.dtype, A.shape[0])])A = np.unique(A)# And to go backA = A.view(A.dtype[0].base)