Reputation: 13
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?
Upvotes: 0
Views: 59
Reputation: 402333
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
Upvotes: 2