You want to find the sort index of the second row of the matrix as argsort and then sort all the columns by row.
import numpy as np
a = np.array([[22, 3, 6, 9, 12, 15],
[4, 2, 1, 6, 8, 3],
[3, 53, 11, 25, 22],
[4, 17, 32, 21, 9],
[46, 31, 7, 16, 29]])
np.argsort(a[1])
a[:, np.argsort(a[1])]
I did it like this, but it doesn't work. Can anyone tell me how to solve it?
python
2 d np the way of a question. If a array soting to be.
The reason why it didn't work was because the two-dimensional list you put in a was a list of different sizes, so a was an np.array on the Python list, not a 2dnp.array. (Because it is not two-dimensional, two-dimensional indexing using and
does not work.)
>>> a = np.array([[22, 3, 6, 9, 12, 15],
[4, 2, 1, 6, 8, 3],
[3, 53, 11, 25, 22],
[4, 17, 32, 21, 9],
[46, 31, 7, 16, 29]])
>>> a
array([list([22, 3, 6, 9, 12, 15]), list([4, 2, 1, 6, 8, 3]),
list([3, 53, 11, 25, 22]), list([4, 17, 32, 21, 9]),
list([46, 31, 7, 16, 29])], dtype=object)
>>> a.shape
(5,)
>>> lens_of_a = [ len(l) for l in a ]
>>> lens_of_a
[6, 6, 5, 5, 5]
>>> b = np.array([[22, 3, 6, 9, 12, 15],
[4, 2, 1, 6, 8, 3],
[3, 53, 11, 25, 22],
[4, 17, 32, 21, 9],
[46, 31, 7, 16, 29]])
>>> b = np.array([[22, 3, 6, 9, 12],
[4, 2, 1, 6, 8],
[3, 53, 11, 25, 22],
[4, 17, 32, 21, 9],
[46, 31, 7, 16, 29]])
>>> b
array([[22, 3, 6, 9, 12],
[ 4, 2, 1, 6, 8],
[ 3, 53, 11, 25, 22],
[ 4, 17, 32, 21, 9],
[46, 31, 7, 16, 29]])
>>> b.shape
(5, 5)
>>> b[:,np.argsort(b[1])]
array([[ 6, 3, 22, 9, 12],
[ 1, 2, 4, 6, 8],
[11, 53, 3, 25, 22],
[32, 17, 4, 21, 9],
[ 7, 31, 46, 16, 29]])
>>> b[1].argsort()
array([2, 1, 0, 3, 4], dtype=int64)
>>> b[:,b[1].argsort()]
array([[ 6, 3, 22, 9, 12],
[ 1, 2, 4, 6, 8],
[11, 53, 3, 25, 22],
[32, 17, 4, 21, 9],
[ 7, 31, 46, 16, 29]])
© 2024 OneMinuteCode. All rights reserved.