Python (Numpy) array sorting Python (Numpy) array sorting numpy numpy

Python (Numpy) array sorting


Try

v[v[:,0].argsort()]

(with v being the array). v[:,0] is the first column, and .argsort() returns the indices that would sort the first column. You then apply this ordering to the whole array using advanced indexing. Note that you get a sorte copy of the array.

The only way I know of to sort the array in place is to use a record dtype:

v.dtype = [("x", float), ("y", float), ("z", float)]v.shape = v.sizev.sort(order="x")


Alternatively

Try

import numpy as nporder = v[:, 0].argsort()sorted = np.take(v, order, 0)

'order' has the order of the first row.and then 'np.take' take the columns their corresponding order.

See the help of 'np.take' as

help(np.take)

take(a, indices, axis=None, out=None, mode='raise') Take elements from an array along an axis.

This function does the same thing as "fancy" indexing (indexing arraysusing arrays); however, it can be easier to use if you need elementsalong a given axis.Parameters----------a : array_like    The source array.indices : array_like    The indices of the values to extract.axis : int, optional    The axis over which to select values. By default, the flattened    input array is used.out : ndarray, optional    If provided, the result will be placed in this array. It should    be of the appropriate shape and dtype.mode : {'raise', 'wrap', 'clip'}, optional    Specifies how out-of-bounds indices will behave.    * 'raise' -- raise an error (default)    * 'wrap' -- wrap around    * 'clip' -- clip to the range    'clip' mode means that all indices that are too large are

replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

Returns-------subarray : ndarray    The returned array has the same type as `a`.See Also--------ndarray.take : equivalent methodExamples-------->>> a = [4, 3, 5, 7, 6, 8]>>> indices = [0, 1, 4]>>> np.take(a, indices)array([4, 3, 6])In this example if `a` is an ndarray, "fancy" indexing can be used.>>> a = np.array(a)>>> a[indices]array([4, 3, 6])


If you have instances where v[:,0] has some identical values and you want to secondarily sort on columns 1, 2, etc.., then you'll want to use numpy.lexsort() or numpy.sort(v, order=('col1', 'col2', etc..) but for the order= case, v will need to be a structured array.