0

Let's say I have a 2D numpy array, and I want to sort it as if it was a standard Python list, i.e. putting its rows themselves in (lexicographical) order, as opposed to the cells along an axis. So from this:

>>> a = np.array([[1, 3], [2, 1], [1, 2]]
array([[1, 3],
       [2, 1],
       [1, 2]])

I want to arrive at this:

array([[1, 2],
       [1, 3],
       [2, 1]])

Unfortunately, it is not so easy:

>>> np.sort(a, axis=0)
array([[1, 1],
       [1, 2],
       [2, 3]])

>>> sorted(list(a))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> np.sort(list(a))
array([[1, 1],
       [1, 2],
       [2, 3]])

I know this might (should!) be super basic, but I cannot, for the life of me, figure out how to do it. Thanks!

David Nemeskey
  • 640
  • 1
  • 5
  • 16

1 Answers1

1

OK, never mind, duplicate of Sorting a 2D numpy array by multiple axes; just use lexsort (or the other alternatives under that question):

>>> a[np.lexsort((a[:, 1], a[:, 0]))]
array([[1, 2],
       [1, 3],
       [2, 1]])
Community
  • 1
  • 1
David Nemeskey
  • 640
  • 1
  • 5
  • 16