numpy的行向量转换为列向量 [英] numpy convert row vector to column vector
问题描述
matrix1 = np.array([[1,2,3],[4,5,6]])
vector1 = matrix1[:,0] # this should have shape (2,1) but actually has (2,)
matrix2 = np.array([[2,3],[5,6]])
np.hstack((vector1, matrix2))
ValueError: all the input arrays must have same number of dimensions
问题是,当我选择矩阵的第一列,把它放在向量1,它被转换成一个行向量,所以当我尝试用矩阵2来连接,我得到一个尺寸误差。我能做到这一点。
The problem is that when I select the first column of matrix1 and put it in vector1, it gets converted to a row vector, so when I try to concatenate with matrix2, I get a dimension error. I could do this.
np.hstack((vector1.reshape(matrix2.shape[0],1), matrix2))
但是,这看起来太丑陋的人,我做我每次来连接矩阵和矢量时间。有没有一种简单的方法来做到这一点?
But this looks too ugly for me to do every time I have to concatenate a matrix and a vector. Is there a simpler way to do this?
推荐答案
更简单的方法是
vector1 = matrix1[:,0:1]
有关的原因,让我向您推荐矿的另一个答案:
For the reason, let me refer you to another answer of mine:
当你写的东西,比如 A [4]
,这是访问数组的第五个元素,而不是给你的原始数组的某些部分的视图。因此,举例来说,如果一个是数字数组,那么 A [4]
将只是一个数字。如果 A
是一个二维数组,即有效数组的数组,那么 A [4]
将是一个一维阵列。基本上,访问数组元素的操作返回的东西与小于原来阵列的维数。
When you write something like
a[4]
, that's accessing the fifth element of the array, not giving you a view of some section of the original array. So for instance, if a is an array of numbers, thena[4]
will be just a number. Ifa
is a two-dimensional array, i.e. effectively an array of arrays, thena[4]
would be a one-dimensional array. Basically, the operation of accessing an array element returns something with a dimensionality of one less than the original array.
这篇关于numpy的行向量转换为列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!