Python numpy和pandas矩阵维度
我的变量如下所示:Python numpy和pandas矩阵维度,python,pandas,numpy,Python,Pandas,Numpy,我的变量如下所示: data.head() Ones Population Profit 0 1 6.1101 17.5920 1 1 5.5277 9.1302 2 1 8.5186 13.6620 3 1 7.0032 11.8540 4 1 5.8598 6.8233 X = data.iloc[:, 0:cols] y = data.iloc[:, co
data.head()
Ones Population Profit
0 1 6.1101 17.5920
1 1 5.5277 9.1302
2 1 8.5186 13.6620
3 1 7.0032 11.8540
4 1 5.8598 6.8233
X = data.iloc[:, 0:cols]
y = data.iloc[:, cols]
X1 = np.matrix(X.values)
y1 = np.matrix(y.values)
X.shape
>>(97, 2)
y.shape
>>(97,)
X1.shape
>>(97, 2)
y1.shape
>>(1, 97)
数据
位于框架中
我期望y1的尺寸是97 X 1,但它是1 X 97。不知怎的,Y1在中间颠倒了,我不明白为什么会这样。由于我最初的y熊猫阵列是97 X 1,我认为y1也应该是相同的,但显然它不是这样工作的
有什么解释吗?
y.values
将列转换为一个numpy数组,该数组有一维,如
[1, 2, 3, 4, 5]
如果对该数组调用np.matrix
,它将返回
[[1, 2, 3, 4, 5]]
但是,如果在调用np.matrix
之前先将一维数组转换为二维数组,则会得到(5,1)矩阵
未经请求的建议,不建议使用矩阵。它给你买的最大的东西是矩阵乘法的操作符
*
,但是使用python的3.5 matmul操作符@
,这并不是必需的
也就是说,这里需要注意的关键点是,y
的形状不是97 x 1,而是97,这是一个一维数组。numpy矩阵
始终是二维的,按照惯例,一维数组被转换为1x
矩阵
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a
array([1, 2, 3, 4, 5])
>>> np.matrix(a).shape
(1, 5)
>>> a.reshape(-1, 1)
array([[1],
[2],
[3],
[4],
[5]])
>>> np.matrix(a.reshape(-1, 1)).shape
(5, 1)
>>> np.matrix(a.reshape(-1, 1))
matrix([[1],
[2],
[3],
[4],
[5]])