0

So I'm trying to sort an array like this by the third item in the array:

[[591 756   3]
 [296 669   7]
 [752 560   2]
 [476 474   0]
 [214 459   1]
 [845 349   6]
 [122 145   4]
 [476 125   5]
 [766 110   8]]

so it would look like

[[476 474   0]
 [214 459   1]
 [752 560   2]
 [591 756   3]
 ....and so on]

This is the code I'm currently using:

sortedanswers = sorted(answithcpoints,key=lambda x:x[2])

but printing sortedanswers would output something like

[array([476, 474,   0]), array([214, 459,   1]), array([752, 560,   2]), array([591, 756,   3]), array([122, 145,   4]), array([476, 125,   5]), array([845, 349,   6]), array([296, 669,   7]), array([766, 110,   8])]

seems to be some sort of array inside the array?

Does anyone know why it's doing this?

2
  • Numpy array? You can argsort on the last column and re-index. Commented Nov 24, 2017 at 3:43
  • Your desired output is also a structure of arrays within an array; what do you really want? Commented Nov 24, 2017 at 3:44

1 Answer 1

2

If you're dealing with numpy arrays, don't bring sorted into this. Call argsort on the last column, and use the sorted indices to re-arrange the array -

arr[arr[:, -1].argsort()]

array([[476, 474,   0],
       [214, 459,   1],
       [752, 560,   2],
       [591, 756,   3],
       [122, 145,   4],
       [476, 125,   5],
       [845, 349,   6],
       [296, 669,   7],
       [766, 110,   8]])

  • arr[:, -1] grabs the last column from arr

    arr[:, -1]
    array([3, 7, 2, 0, 1, 6, 4, 5, 8])
    
  • arr[:, -1].argsort() - sorts arr's last column based on its indices. The result is an array of sorted indices of x

    arr[:, -1].argsort()
    array([3, 4, 2, 0, 6, 7, 5, 1, 8])
    
  • arr[arr[:, -1].argsort()] indexes rows in arr based on the contents of the sorted indices from the previous step

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

1 Comment

this worked wonderfully thank you! for education purposes, would you mind explaining the line a little bit? what does array[:,-1] actually mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.