Sorting numpy 3d array with two axis sort constraints
I have a 3-D numpy array that I would like to sort.
Array example:
arr = numpy.array([[4., 5., .1], [-2., 5., .3], [-1., -3., .2], [5, -4, .1], [2., 2., .25], [-2., 0., .1], [-1.5, 0., .1], [1., -3., .1], [-2., 8, .1]])
For convenience, let's call three dimensions x
, y
and z
respectively. I would like to sort my array based on value y
in descending order. I know I can do it with
arr[arr[:, 1].argsort()[::-1]]
However, the second limitation is that for multiple occurrences of the same value, y
I would like to sort along x
in ascending value. The values x
and y
can be negative.
I've tried sorting first along x and then along y, hoping that the order of x stays in the tick. Unfortunately, this is not the case.
The sorted array arr
must be given
sorted_arr = numpy.array([[-2., 8, .1], [-2., 5., .3], [4., 5., .1], [2., 2., .25], [-2., 0., .1], [-1.5, 0., .1], [-1., -3., .2], [1., -3., .1], [5, -4, .1]])
Since the actual array is very large, I don't want to use loops for
. How can I sort the array?
source to share
One way could be to use np.lexsort
to sort by the second column followed by the first column.
Since this sorts the values ββin ascending order by default, you can multiply the second column by -1 to "flip" the values ββso that those values ββare sorted from high to low.
The function returns an array of indices that can be used to change the order of the rows arr
:
>>> arr[np.lexsort((arr[:, 0], -arr[:, 1]))]
array([[-2. , 8. , 0.1 ],
[-2. , 5. , 0.3 ],
[ 4. , 5. , 0.1 ],
[ 2. , 2. , 0.25],
[-2. , 0. , 0.1 ],
[-1.5 , 0. , 0.1 ],
[-1. , -3. , 0.2 ],
[ 1. , -3. , 0.1 ],
[ 5. , -4. , 0.1 ]])
source to share