-1

I have a numpy array

array([[ 4.14022471,  3.96360618],  
       [ 0.37601032,  1.25528411],  
       [ 3.49313049,  0.94909878]]) 

Now I wish to sort this array's rows with respect to the norm of the rows, i.e

norm([ 4.14022471,  3.96360618]) = 5.73163455
norm([ 0.37601032,  1.25528411]) = 1.31039
norm([ 3.49313049,  0.94909878]) = 3.61977197

Hence the first row remains in first position, while 2nd and 3rd rows need to be swapped.

The solution will be

array([[ 4.14022471,  3.96360618],    
       [ 3.49313049,  0.94909878],
       [ 0.37601032,  1.25528411]])

How can I do this?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Formal_this
  • 121
  • 5
  • Does this answer your question? [Sort array's rows by another array in Python](https://stackoverflow.com/questions/9007877/sort-arrays-rows-by-another-array-in-python) For the "another array" by which you will sort, see [How to apply numpy.linalg.norm to each row of a matrix?](https://stackoverflow.com/q/7741878/843953) – Pranav Hosangadi Feb 10 '23 at 22:13

3 Answers3

1

With numpy.argsort and numpy.take:

arr = np.array([[ 4.14022471, 3.96360618], [ 0.37601032, 1.25528411], [ 3.49313049, 0.94909878]])
norms = np.linalg.norm(arr, axis=1)
arr_sorted = np.take(arr, np.argsort(norms)[::-1], axis=0)

[[4.14022471 3.96360618]
 [3.49313049 0.94909878]
 [0.37601032 1.25528411]]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
-1

Python's built-in sorted() function has a key parameter that accepts a function, simply pass in the norm function and reverse=True to sort largest to smallest

>>> arr = array([[ 4.14022471,3.96360618],[ 0.37601032,1.25528411],[3.49313049, 0.94909878]])
>>> array(sorted(arr, key=norm, reverse = True))
array([[4.14022471, 3.96360618],
       [3.49313049, 0.94909878],
       [0.37601032, 1.25528411]])
AnrimO
  • 1
-1

For your task it is enough to use the only library - numpy. Solution:

a = np.array([[ 4.14022471,  3.96360618],   [ 0.37601032,  1.25528411],   [ 3.49313049,  0.94909878]])

def get_norm(array):
    return np.linalg.norm(array)

sorted(a, reverse=True, key = get_norm)

It will be appropriate to use the lambda function. It's more concise and easier to read the code.

a = np.array([[ 4.14022471,  3.96360618],   [ 0.37601032,  1.25528411],   [ 3.49313049,  0.94909878]])
sorted(a, reverse=True, key = lambda x:np.linalg.norm(x))

In both cases the program will output:

[array([4.14022471, 3.96360618]),
 array([3.49313049, 0.94909878]),
 array([0.37601032, 1.25528411])]