Massyanya Massyanya - 1 month ago 8
Python Question

Sorting arrays in Python by a non-integer column

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?

What would you recommend?

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
I get the following error:
Type Error: only integer scalar arrays can be converted to a scalar index

Answer Source

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]]