在 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屋!