Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the inverse of a matrix with pandas

I have a large pandas.DataFrame - which is a square matrix with header and index, and I am trying to use pandas' capabilities to calculate the inverse of that matrix, without going directly through numpy.

I want to stay within a pandas framework to keep the headings of my data frame. I could use the pandas.as_matrix() function, but that turns it into an ndarray and I loose all the information provided by the headings.

Any suggestions?

like image 508
Polo.B Avatar asked Nov 29 '16 06:11

Polo.B


People also ask

How do you find the inverse of a matrix in python?

Python provides a very easy method to calculate the inverse of a matrix. The function numpy. linalg. inv() which is available in the python NumPy module is used to compute the inverse of a matrix.

How do you calculate the inverse of a matrix?

To find the inverse of a 2x2 matrix: swap the positions of a and d, put negatives in front of b and c, and divide everything by the determinant (ad-bc).

What is the Numpy method to calculate the inverse of a matrix?

We use numpy. linalg. inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.


1 Answers

consider the dataframe df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('xyz'))
df

enter image description here

calculate the inverse (with numpy, let's not be crazy)

df_inv = pd.DataFrame(np.linalg.pinv(df.values), df.columns, df.index)
df_inv

enter image description here

notice I use pinv for the pseudo inverse

then check

df_inv.dot(df)

enter image description here

like image 130
piRSquared Avatar answered Sep 20 '22 15:09

piRSquared