pandas 用熊猫计算矩阵的逆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40858835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:32:08  来源:igfitidea点击:

Calculating the inverse of a matrix with pandas

pythonpandasnumpymatrix

提问by Polo.B

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.

我有一个大 Pandas DataFrame——它是一个带有标题和索引的方阵,我正在尝试使用 Pandas 的功能来计算该矩阵的逆,而不是直接通过 numpy。

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

我想留在Pandas框架内以保留数据框的标题。我可以使用 pd.as_matrix 函数,但这会将它变成一个 ndarray 并且我丢失了标题提供的所有信息。

Any suggestions?

有什么建议?

回答by piRSquared

consider the dataframe df

考虑数据框 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)

计算逆(用 numpy,让我们不要发疯)

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

enter image description here

在此处输入图片说明

notice I use pinvfor the pseudo inverse

注意我pinv用于伪逆

then check

然后检查

df_inv.dot(df)

enter image description here

在此处输入图片说明