sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python

PythonSortingNumpy

Python Problem Overview


I'm using numpy.linalg.eig to obtain a list of eigenvalues and eigenvectors:

A = someMatrixArray
from numpy.linalg import eig as eigenValuesAndVectors

solution = eigenValuesAndVectors(A)

eigenValues = solution[0]
eigenVectors = solution[1]

I would like to sort my eigenvalues (e.g. from lowest to highest), in a way I know what is the associated eigenvector after the sorting.

I'm not finding any way of doing that with python functions. Is there any simple way or do I have to code my sort version?

Python Solutions


Solution 1 - Python

Use numpy.argsort. It returns the indices one would use to sort the array.

import numpy as np
import numpy.linalg as linalg

A = np.random.random((3,3))
eigenValues, eigenVectors = linalg.eig(A)

idx = eigenValues.argsort()[::-1]   
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

If the eigenvalues are complex, the sort order is lexicographic (that is, complex numbers are sorted according to their real part first, with ties broken by their imaginary part).

Solution 2 - Python

Above answer by unutbu is very crisp and concise. But, here is another way we can do it which more general and can be used for lists as well.

eval, evec =  sp.eig(A)
ev_list = zip( eval, evec )
ev_list.sort(key=lambda tup:tup[0], reverse=False)
eval, evec = zip(*ev_list)

This tup[0] is the eigenvalue based on which the sort function will sort the list.

reverse = False is for increasing order.

Solution 3 - Python

The ubuntu's piece of code doesn't work on my Python 3.6.5. It leads run-time errors. So, I refactored his/her code to this one which works ok on my test cases:

import numpy as np
from numpy import linalg as npla
#
def eigen(A):
	eigenValues, eigenVectors = npla.eig(A)
	idx = np.argsort(eigenValues)
	eigenValues = eigenValues[idx]
	eigenVectors = eigenVectors[:,idx]
	return (eigenValues, eigenVectors)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJorge LeitaoView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonShikharDuaView Answer on Stackoverflow
Solution 3 - Pythonstd.approachView Answer on Stackoverflow