I have a 2D numpy array of shape (N,2) which is holding N points (x and y coordinates). For example:
array([[3, 2],
[6, 2],
[3, 6],
[3, 4],
[5, 3]])
I'd like to sort it such that my points are ordered by x-coordinate, and then by y in cases where the x coordinate is the same. So the array above should look like this:
array([[3, 2],
[3, 4],
[3, 6],
[5, 3],
[6, 2]])
If this was a normal Python list, I would simply define a comparator to do what I want, but as far as I can tell, numpy's sort function doesn't accept user-defined comparators. Any ideas?
EDIT: Thanks for the ideas! I set up a quick test case with 1000000 random integer points, and benchmarked the ones that I could run (sorry, can't upgrade numpy at the moment).
Mine: 4.078 secs
mtrw: 7.046 secs
unutbu: 0.453 secs
The title says "sorting 2D arrays". Although the questioner uses an
(N,2)
-shaped array, it's possible to generalize unutbu's solution to work with any(N,M)
array, as that's what people might actually be looking for.One could
transpose
the array and use slice notation with negativestep
to pass all the columns tolexsort
in reversed order:I was struggling with the same thing and just got help and solved the problem. It works smoothly if your array have column names (structured array) and I think this is a very simple way to sort using the same logic that excel does:
Note the double-brackets enclosing the sorting criteria. And off course, you can use more than 2 columns as sorting criteria.
EDIT: removed bad answer.
Here's one way to do it using an intermediate structured array:
which gives the desired output:
Not sure if this is quite the best way to go about it though.
Using lexsort:
a.ravel()
returns a view ifa
isC_CONTIGUOUS
. If that is true, @ars's method, slightly modifed by usingravel
instead offlatten
, yields a nice way to sorta
in-place:Since
b
is a view ofa
, sortingb
sortsa
as well:I found one way to do it:
It's pretty terrible to have to sort twice (and use the plain python
sorted
function instead of a faster numpy sort), but it does fit nicely on one line.The numpy_indexed package (disclaimer: I am its author) can be used to solve these kind of processing-on-nd-array problems in an efficient fully vectorized manner: