Say I have a NumPy array:
[[4 9 2]
[5 1 3]]
I want to sort the bottom row of this array, but have the top row follow the sorting, such that I get:
[[9 2 4]
[1 3 5]]
I know that you can sort like this using the sorted() function, but that requires input and output of lists.
Any ideas? Thanks so much!
import numpy as np
a = np.array([[4,9,2],[5,1,3]])
idx = np.argsort(a[1])
Now you can use idx to index your array:
b=a[:,idx]
The only (efficient) solution I can think of needs a copy of the original array.
import numpy as np
a = np.array([[4,9,2],[5,1,3]])
idx = np.argsort(a[1])
So, that idx
is the index of the sorted column.
c = a.copy()
for i in range(len(idx)):
a[:,i] = c[:,idx[i]]
That should be reasonably fast, but, of course, wastes some memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With