So for example I have an array that I want to sort by a column in an ascending order, and it's easy to do for integers using 'sorting()', 'np.arrange()', or 'np.argsort()'.
However, what if my column is consisting of floats?
Edit: I mean, I have something like:
a = array([[1.7, 2, 3],
[4.5, 5, 6],
[0.1, 0, 1]])
and I want to get this:
array([[0.1, 0, 1],
[1.7, 2, 3],
[4.5, 5, 6]])
So far with argsort()
I get the following error: Type Error: only integer scalar arrays can be converted to a scalar index
You can use a standard Python's sorted
(or sort
for in-place sorting), no matter what is contained in the sequence. Just use a custom key
, or a custom compare function ( cmp
). For example, to sort a list of lists (2-d array) ascending by 4th column:
>>> a=[[1.0,2.0,3.0,4.0], [4.0,3.0,2.0,1.0], [0,0,0,0]]
>>> from operator import itemgetter
>>>> sorted(a, key=itemgetter(3))
[[0, 0, 0, 0], [4.0, 3.0, 2.0, 1.0], [1.0, 2.0, 3.0, 4.0]]
The standard way to do this in numpy
is to specify the correct axis
you want to sort on, by default it sorts on axis=-1
:
>>> np.sort(a, axis=0)
array([[ 0.1, 0. , 1. ],
[ 1.7, 2. , 3. ],
[ 4.5, 5. , 6. ]])
Or inplace:
>>> a.sort(axis=0)
>>> a
array([[ 0.1, 0. , 1. ],
[ 1.7, 2. , 3. ],
[ 4.5, 5. , 6. ]])
To sort just on a specific column you can use argsort()
, eg column 0
:
>>> a[np.argsort(a[:,0])]
array([[ 0.1, 0. , 1. ],
[ 1.7, 2. , 3. ],
[ 4.5, 5. , 6. ]])
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.