加入两个numpy矩阵

时间:2012-09-03 11:11:15

标签: python multidimensional-array matrix numpy scipy

如果你有两个numpy矩阵,你如何将它们合并为一个?它们应该水平连接,以便

[[0]         [1]               [[0][1]
 [1]     +   [0]         =      [1][0]
 [4]         [1]                [4][1]
 [0]]        [1]]               [0][1]]

例如,使用这些矩阵:

>>type(X)
>>type(Y)
>>X.shape
>>Y.shape
<class 'numpy.matrixlib.defmatrix.matrix'>
<class 'numpy.matrixlib.defmatrix.matrix'>
(53, 1)
(53, 1)

我尝试过hstack但收到错误:

>>Z = hstack([X,Y])

Traceback (most recent call last):
  File "labels.py", line 85, in <module>
    Z = hstack([X, Y])
  File "C:\Python27\lib\site-packages\scipy\sparse\construct.py", line 263, in h
stack
    return bmat([blocks], format=format, dtype=dtype)
  File "C:\Python27\lib\site-packages\scipy\sparse\construct.py", line 329, in b
mat
    raise ValueError('blocks must have rank 2')
ValueError: blocks must have rank 2

1 个答案:

答案 0 :(得分:12)

从追溯来看,似乎你已经完成了from scipy.sparse import *或类似的事情,因此numpy.hstackscipy.sparse.hstack遮蔽了。 numpy.hstack工作正常:

>>> X = np.matrix([[0, 1, 4, 0]]).T
>>> Y = np.matrix([[1, 0, 1, 1]]).T
>>> np.hstack([X, Y])
matrix([[0, 1],
        [1, 0],
        [4, 1],
        [0, 1]])