Answer a question

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?

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

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐