2

I am having troubles working with NumPy arrays as I am new to NumPy. I have a big input which I read with sys.stdin, which is consisted of lines with 2 values and a space between them, representing a point or two coordinates. I then save it in a list which looks something like this:

np.array([[1, 3], [5, 6], [7, 2], [9, 9]]) 

I want to sort the list by their sums and then by their x-coordinate, but I am not sure how to do this.

I am also not sure how would I add that sum as the third element of each sublist, in case I wanted to add it.

3
  • Is this Python2.7 or 3? Commented Jan 16, 2016 at 12:26
  • What would be the expected output for the sample data? Commented Jan 16, 2016 at 12:33
  • Is you data already sorted by the x coordinate? Commented Jan 16, 2016 at 12:47

1 Answer 1

3

Relying on python's built-in sorted is inefficient for numpy-arrays, especially when these are big. Try this instead:

import numpy as np l = np.array([[1, 3], [5, 6], [7, 2], [9, 9]]) ind = np.lexsort((l[:,0], l.sum(axis=1))) sorted_l = l[ind] 

ind will contain the indices of your original array, sorted by the two arrays given to lexsort. The last array is the primary sort column for lexsort. l[ind] selects these indices from your original array.

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer but I think you edited it the wrong way by mistake. The first answer gave me the result I wanted, now it sorts by x coordinate and then by sums :)
Hu, weird. I first posted without testing the code and then edited after testing, because it gave the wrong result. The docs also say the last column is the primary column. I"ll check again
@Larisa It is correct that you are expecting array([[1, 3], [7, 2], [5, 6], [9, 9]]), right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.