为什么我要为DataFrame点函数获取矩阵未对齐的错误?

问题描述 投票:0回答:1

我正在尝试使用Numpy和Pandas在Python中实现简单的线性回归。但是我收到一个ValueError:矩阵未对齐错误,调用点函数实际上是按照文档所述计算矩阵乘法。以下是代码段:

import numpy as np
import pandas as pd

#initializing the matrices for X, y and theta
#dataset = pd.read_csv("data1.csv")
dataset = pd.DataFrame([[6.1101,17.592],[5.5277,9.1302],[8.5186,13.662],[7.0032,11.854],[5.8598,6.8233],[8.3829,11.886],[7.4764,4.3483],[8.5781,12]])
X = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
X.insert(0, "x_zero", np.ones(X.size), True)
print(X)
print(f"\n{y}")
theta = pd.DataFrame([[0],[1]])
temp = pd.DataFrame([[1],[1]])
print(X.shape)
print(theta.shape)
print(X.dot(theta))

这是相同的输出:

   x_zero       0
0     1.0  6.1101
1     1.0  5.5277
2     1.0  8.5186
3     1.0  7.0032
4     1.0  5.8598
5     1.0  8.3829
6     1.0  7.4764
7     1.0  8.5781

0    17.5920
1     9.1302
2    13.6620
3    11.8540
4     6.8233
5    11.8860
6     4.3483
7    12.0000
Name: 1, dtype: float64
(8, 2)
(2, 1)
Traceback (most recent call last):
  File "linear.py", line 16, in <module>
    print(X.dot(theta))
  File "/home/tejas/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 1063, in dot
    raise ValueError("matrices are not aligned")
ValueError: matrices are not aligned

您可以看到它们的形状属性的输出,第二个轴具有相同的尺寸(2),点函数应返回8 * 1 DataFrame。然后,为什么会出错?

python-3.x pandas
1个回答
0
投票

这种错位不是来自形状的,而是来自熊猫索引的。您有2个解决问题的方法:

调整theta分配:

theta = pd.DataFrame([[0],[1]], index=X.columns)

因此您乘以的索引将匹配。

通过将第二个df移至numpy,删除索引的相关性:

X.dot(theta.to_numpy())
© www.soinside.com 2019 - 2024. All rights reserved.