python - Sort three dimensional numpy array with two axes sorting constraints -


i have 3 dimensional numpy array sort.

an example of array given by:

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

lets convenience call 3 dimensions x, y, , z, respectively. sort array based on value of y in decreasing order. know can by

arr[arr[:, 1].argsort()[::-1]] 

however, second constraint multiple occurrences of same y-value sort along x in increasing value. values of x , y can both negative.

i have tried sorting first along x , along y hope x order remain in tact. unfortunately not case.

the sorted array of arr should given by

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 actual array big not want use for loops. how can sort array?

one way use np.lexsort sort second column followed first column.

since sorts values in ascending order default, multiply second column -1 "flip" values these values sorted high-to-low instead.

the function returns array of indices can use reorder rows of 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 ]]) 

Comments

Popular posts from this blog

c# - Where does the .ToList() go in LINQ query result -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -