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时,我得到一个尺寸错误。我能做到。
np.hstack((vector1.reshape(matrix2.shape[0],1), matrix2))
但这看起来太难看了,我不能每次连接一个矩阵和一个向量。有没有更简单的方法来做这件事?
发布于 2013-07-13 03:56:23
更简单的方法是
vector1 = matrix1[:,0:1]
出于这个原因,让我向您推荐another answer of mine
当你写像
a[4]
这样的东西时,这是在访问数组的第五个元素,而不是让你看到原始数组的某些部分。例如,如果a是一个数字数组,那么a[4]
将只是一个数字。如果a
是二维数组,即实际上是数组的数组,那么a[4]
就是一维数组。基本上,访问数组元素的操作返回的维数比原始数组少1。
发布于 2013-07-13 03:55:57
以下是其他三个选项:
np.hstack((vector1.reshape(-1,1),matrix2))
np.newaxis
(或等效的None
)进行索引,以插入大小为1的新轴:np.hstack((vector1:,np.newaxis,matrix2)) np.hstack((vector1:,None,matrix2))
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))
发布于 2021-11-06 04:32:33
子设置
更简单的方法是对矩阵进行子集。
>>> matrix1
[[1 2 3]
[4 5 6]]
>>> matrix1[:, [0]] # Subsetting
[[1]
[4]]
>>> matrix1[:, 0] # Indexing
[1 4]
>>> matrix1[:, 0:1] # Slicing
[[1]
[4]]
我也在一个类似的问题中mentioned了这个。
它的工作原理有点类似于熊猫数据帧。如果您为数据帧建立索引,它将为您提供系列。如果您对数据帧进行子集或切片,它将为您提供数据帧。
您的方法使用索引,David Z's approach使用切片,而我的方法使用子集。
https://stackoverflow.com/questions/17622905
复制相似问题