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

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -