1

I have a simple 2-dimensional array that I would like to sort by the entry in the 2nd column, and if identical entries exist in the 2nd column, then also sort by the 1st column and return the indices of this new array from the original array, a. Here is the starting point:

import numpy as np
a = np.array([[0.1,2.134],[0.2,3.02],[0.1,2.5],[0.3,2.134],[0.1,3.02]])
a
>>> array([[0.1  , 2.134],
   [0.2  , 3.02 ],
   [0.1  , 2.5  ],
   [0.3  , 2.134],
   [0.1  , 3.02 ]])

which I can then sort by the 2nd column to produce:

b = a[a[:,1].argsort()]
b
>>> array([[0.1  , 2.134],
   [0.3  , 2.134],
   [0.1  , 2.5  ],
   [0.2  , 3.02 ],
   [0.1  , 3.02 ]])

but I would like this additionally sorted by the 1st column. My desired output starting from a is:

>>> array([[0.1  , 2.134],
   [0.3  , 2.134],
   [0.1  , 2.5  ],
   [0.1  , 3.02 ],
   [0.2  , 3.02 ]])

along with the corresponding indices of this new array.

Mathews24
  • 681
  • 10
  • 30
  • 1
    Check this [solution](https://stackoverflow.com/questions/2706605/sorting-a-2d-numpy-array-by-multiple-axes) – vb_rises May 02 '19 at 00:39

1 Answers1

0

IIUC lexsort

a[np.lexsort((a[:,0], a[:,1]))]
array([[0.1  , 2.134],
       [0.3  , 2.134],
       [0.1  , 2.5  ],
       [0.1  , 3.02 ],
       [0.2  , 3.02 ]])
BENY
  • 317,841
  • 20
  • 164
  • 234