Sorting coordinates array

  • Thread starter Maarten van Reeuwijk
  • Start date
M

Maarten van Reeuwijk

I'm a newbie to Python, so sorry for this maybe trivial question. I have a
numpy array with coordinates, which I want to sort, for example first on
z-coordinate, then x and lastly y-coordinate. So an array like:

[[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]]

should look after sorting like

[[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]]

I tried the sort command, but that command mangles my coordinate pairs. Also
converting the array to a list doesn't seem to improve the results. How
should I tackle this problem?

TIA, Maarten
 
V

Ville Vainio

Maarten van Reeuwijk said:
I'm a newbie to Python, so sorry for this maybe trivial question. I have a
numpy array with coordinates, which I want to sort, for example first on
z-coordinate, then x and lastly y-coordinate. So an array like:

Implement a comparison function:
Help on built-in function sort:

sort(...)
L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1


Alternatively, you could take a look at DSU pattern (Decorate, Sort,
Undecorate):

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234
 
P

Peter Otten

Maarten said:
I'm a newbie to Python, so sorry for this maybe trivial question. I have a
numpy array with coordinates, which I want to sort, for example first on
z-coordinate, then x and lastly y-coordinate. So an array like:

[[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]]

should look after sorting like

[[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]]

I tried the sort command, but that command mangles my coordinate pairs.
Also converting the array to a list doesn't seem to improve the results.
How should I tackle this problem?
import Numeric
a = Numeric.array([[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]])
lst = a.tolist()
lst.sort(lambda x, y: cmp(x[::-1], y[::-1]))
lst [[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]]

You can pass an arbitrary comparison function to list.sort(), I just compare
reversed copies of the inner lists.
This is a highly unoptimized version, but at least seems to do the job.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top