在NumPy中将行向量转换为列向量

sia*_*mii 21 python arrays numpy matrix

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
Run Code Online (Sandbox Code Playgroud)

问题是当我选择matrix1的第一列并将其放在vector1中时,它会转换为行向量,所以当我尝试与matrix2连接时,我得到一个维度错误.我能做到这一点.

np.hstack((vector1.reshape(matrix2.shape[0],1), matrix2))
Run Code Online (Sandbox Code Playgroud)

但是每次我必须连接矩阵和向量时,这对我来说太难看了.有更简单的方法吗?

Dav*_*d Z 26

更简单的方法是

vector1 = matrix1[:,0:1]
Run Code Online (Sandbox Code Playgroud)

因此,让我向您推荐我的另一个答案:

当您编写类似的东西时a[4],它正在访问数组的第五个元素,而不是为您提供原始数组的某些部分的视图.因此,例如,如果a是一个数字数组,那么a[4]它只是一个数字.如果a是二维数组,即实际上是数组数组,那么a[4]它将是一维数组.基本上,访问数组元素的操作返回的维度比原始数组小1.


ali*_*i_m 16

以下是其他三个选项:

  1. 您可以通过允许隐式设置向量的行维度来稍微整理您的解决方案:

    np.hstack((vector1.reshape(-1, 1), matrix2))
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以使用np.newaxis(或等效None)索引来插入大小为1的新轴:

    np.hstack((vector1[:, np.newaxis], matrix2))
    np.hstack((vector1[:, None], matrix2))
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您可以使用np.matrix,对具有整数的列建立索引始终返回列向量:

    matrix1 = np.matrix([[1, 2, 3],[4, 5, 6]])
    vector1 = matrix1[:, 0]
    matrix2 = np.matrix([[2, 3], [5, 6]])
    np.hstack((vector1, matrix2))
    
    Run Code Online (Sandbox Code Playgroud)