在NumPy中将行向量转换为列向量 [英] Convert row vector to column vector in NumPy
问题描述
import numpy as np
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
问题在于,当我选择matrix1的第一列并将其放入vector1时,它将转换为行向量,因此当我尝试与matrix2串联时,会出现尺寸错误.我可以做到的.
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是一个数字数组,则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屋!