【问题标题】:Why I am getting matrices are not aligned error for DataFrame dot function?为什么我收到 DataFrame 点函数的矩阵未对齐错误?
【发布时间】:2023-03-20 18:40:01
【问题描述】:

我正在尝试使用 Numpy 和 Pandas 在 Python 中实现简单的线性回归。但是我得到一个 ValueError: matrices are not aligned 错误,因为它调用了 dot 函数,该函数基本上计算了文档中所说的矩阵乘法。以下是代码sn-p:

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。那么,为什么会报错呢?

【问题讨论】:

  • @Parfait 我的错。我已经编辑了代码并从 csv 中为 DataFrame 放置了一些数据库的起始行。

标签: python-3.x pandas


【解决方案1】:

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

调整theta 分配:

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

所以你相乘的索引会匹配。

通过将第二个 df 移动到 numpy 来删除索引相关性:

X.dot(theta.to_numpy())

这个功能实际上在pandas 中很有用——它会尝试智能匹配索引,你的情况只是一个非常具体的情况,当它变得适得其反时 ;)

【讨论】:

  • 打败我!根据docsDataFrame 的列名和 other 的索引必须包含相同的值
猜你喜欢
  • 2017-01-12
  • 2018-05-27
  • 2012-02-03
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多