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?
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.
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).
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.
consider the dataframe df
np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('xyz'))
df
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
notice I use pinv
for the pseudo inverse
then check
df_inv.dot(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With