How to sort the rows of a numpy matrix with respect to their norm?

Question:

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?

Asked By: Formal_this

||

Answers:

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]])
Answered By: AnrimO

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]]
Answered By: RomanPerekhrest

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])]
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.