1

I'm new to python. This seems like a super easy problem but none of the similar answers I found were relevant to my case.

I have an np.ndarray object, where every row represents a vector, like so:

vectors = [[2, 0, 1]
           [1, 1, 2]
           [3, 2, 0]]

I want to sort those vectors according to the 1st component, without changing the vectors themselves. I.e. I only want to swap entire rows, such that:

 sorted_vectors = [[1, 1, 2]
                   [2, 0, 1]
                   [3, 2, 0]]

I've tried using np.ndarray.sort, but this method will sort every column independently, effectively destroying the vectors.

 vectors.sort(axis=0) = [[1, 0, 0]
                         [2, 1, 1]
                         [3, 2, 2]]

Is there a sorting method that will look at rows or columns as whole objects and order them according the nth element?

Matheus Leão
  • 417
  • 4
  • 12

1 Answers1

0

You can try

import numpy

vectors = [[2, 0, 1],
           [1, 1, 2],
           [3, 2, 0]]

vectors = sorted(vectors)
print (vectors)
r_batra
  • 400
  • 3
  • 14
  • 1
    This doesn't work for numpy array: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). However @cs95 pointed to a relevant solution – Matheus Leão May 23 '19 at 17:57