repurposer
repurposer

Reputation: 145

lexsort zeros before negatives?

I have some data that I want to sort, but this method using numpy.lexsort()

data = np.zeros(shape=(n,6))
# some routine that partially populates the table
index = np.lexsort((data[:,0],data[:,1]))
data = data[index] # sort

used on a table such as

-500    0.5 0.0 0.0 0.0 0.0
-400    0.6 0.0 0.0 0.0 0.0
0.0     0.0 0.0 0.0 0.0 0.0
0.0     0.0 0.0 0.0 0.0 0.0

returns data such as:

0.0     0.0 0.0 0.0 0.0 0.0
0.0     0.0 0.0 0.0 0.0 0.0
-500    0.5 0.0 0.0 0.0 0.0
-400    0.6 0.0 0.0 0.0 0.0

but that's weird, right?

Upvotes: 1

Views: 182

Answers (1)

cge
cge

Reputation: 9888

As seburg noted, what you're seeing is not incorrect. Lexsort sorts by the last key provided, then the second-to-last, and so on, which might seem a bit backward. From the docstring:

The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, it's rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

What you're seeing is correctly sorted given this, but what you probably wanted to do was the following:

data = np.zeros(shape=(n,6))
# some routine that partially populates the table
index = np.lexsort((data[:,1],data[:,0]))
data = data[index] # sort

Upvotes: 1

Related Questions