Skip to main content
 首页 » 编程设计

Python数组/矩阵维度

2025年05月04日12tintown

我创建了两个矩阵

import numpy as np 
arrA = np.zeros((9000,3)) 
arrB = np.zerros((9000,6)) 

我想连接这些矩阵的各个部分。 但是当我尝试这样做时:

arrC = np.hstack((arrA, arrB[:,1])) 

我得到一个错误:

ValueError: all the input arrays must have same number of dimensions 

我猜这是因为 np.shape(arrB[:,1]) 等于 (9000,) 而不是 (9000,1),但我不知道如何解决它。

你能评论一下这个问题吗?

请您参考如下方法:

您可以通过传递索引列表而不是索引来保留维度:

>>> arrB[:,1].shape 
(9000,) 
>>> arrB[:,[1]].shape 
(9000, 1) 
>>> out = np.hstack([arrA, arrB[:,[1]]]) 
>>> out.shape 
(9000, 4)