Skip to main content
 首页 » 编程设计

python之在 Scipy 中使用 Pandas 数据框

2024年10月01日7小虾米

假设一个数据框,df,使用大小为 n x m 的 pandas。

我想对df 进行线性代数运算。

直到现在,我还无法找到一种在df 上直接执行线性代数的方法。我能够找到的是如何使用以下方法将 df 从 pandas 格式转换为 Numpy:

A = DataFrame.as_matrix 

那我就可以简单的做

linalg.inv(A) 

在 Scipy 中是否有使用 pandas dataframe 执行线性运算的直接方法?例如:

linalg.inv(df) 

我想使用 scipy 中的线性代数运算而不是 Numpy 的原因是基于:

In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

来自 What-is-the-difference-between-NumPy-and-SciPy

请您参考如下方法:

您可以直接在您的 DataFrames 上使用它。

演示:

In [111]: from scipy.linalg import inv 
 
In [112]: df = pd.DataFrame(np.random.rand(5,5), columns=list('abcde')) 
 
In [113]: df 
Out[113]: 
          a         b         c         d         e 
0  0.619086  0.229390  0.361611  0.857177  0.274983 
1  0.389630  0.689562  0.687043  0.388781  0.781168 
2  0.702920  0.253870  0.881173  0.858378  0.363035 
3  0.007022  0.571111  0.408729  0.708862  0.042882 
4  0.876747  0.170775  0.499824  0.929295  0.762971 
 
In [114]: inv(df) 
Out[114]: 
array([[ 5.67652746,  1.54854922, -0.21927114, -3.04884324, -3.35567433], 
       [ 4.32996215,  1.99787442, -1.18579234, -0.9802008 , -2.98677673], 
       [-2.43833426, -0.29287732,  2.11691208,  0.34655505,  0.1519223 ], 
       [-1.92398165, -1.43903773, -0.22722582,  1.96404685,  2.16451337], 
       [-3.55144126, -0.28205091, -0.59264783,  1.10366465,  3.09938364]]) 

PS 我使用 Pandas 0.19.2 和 SciPy 0.18.1 进行此演示。

更新:如果你想得到一个 DataFrame 作为结果:

In [4]: pd.DataFrame(inv(df), columns=df.columns, index=df.index) 
Out[4]: 
          a         b         c         d         e 
0  5.676507  1.548541 -0.219275 -3.048828 -3.355657 
1  4.329938  1.997865 -1.185791 -0.980187 -2.986760 
2 -2.438323 -0.292872  2.116913  0.346547  0.151914 
3 -1.923971 -1.439034 -0.227226  1.964040  2.164506 
4 -3.551428 -0.282045 -0.592647  1.103655  3.099373