开发者社区> 问答> 正文

为什么我的DataFrame点函数出现矩阵未对齐错误?

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

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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-21 11:49:53 2878 0
1 条回答
写回答
取消 提交回答
  • 这种错位不是来自形状的错位,而是来自熊猫索引的错位。您有2个解决问题的方法:

    调整theta任务:

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

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

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

    X.dot(theta.to_numpy())
    

    该功能实际上在pandas中很有用-它会尝试智能匹配索引,当您的情况适得其反时,您的情况就是非常具体的情况;)

    回答来源:stackoverflow

    2020-03-21 11:50:10
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
重新定义计算的边界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载