I want to create a matrix by Numpy as follow:
the first column composed by 0 and 1 , in this case , the value is not important the second column composed by integer , I want to sort my matrix by this column.
[[[1,1,1,1,1] , [3]],
[[0,0,0,0,0] , [2]],
[[1,1,1,1,1] , [5]]]
The question is: - How to create matrix like that? - After created , how to sort this matrix by second column
and get the answer as follow:
[ [[0,0,0,0,0] , [2]],
[[1,1,1,1,1] , [3]],
[[1,1,1,1,1] , [5]] ]
I'm fresh in numpy, I tried a lot but didn't succeeded, please help.
In the following, I used newlines to format this code for clarity by putting your matrix rows onto separate lines. This is NOT necessary, but I feel it helps show the content of each row (basically a list with five items and a list with one item).
When defining a numpy array, you can also define the datatype (dtype) with both a field name and the type of data stored in that field. Lists are considered an object
type by numpy, so for each row, I assigned a field name to each item in the row ('x' and 'y') and I assigned a data type of object
.
n = np.array([ ([1,1,1,1,1] , [3]),
([0,0,0,0,0] , [2]),
([0,0,0,0,0] , [5])],
dtype=[('x', object),('y', object)]
Numpy arrays all have a builtin method called .sort()
that enables you to sort the rows. If you give it an order argument using the name of a field, it will sort by the field (ie that column). In this case, we sort by the 'y' field/column.
n.sort(order='y')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.