Zach
Zach

Reputation: 4744

joining two numpy matrices

If you have two numpy matrices, how can you join them together into one? They should be joined horizontally, so that

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

For example, with these matrices:

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

I have tried hstack but get an error:

>>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

Upvotes: 6

Views: 7943

Answers (1)

Fred Foo
Fred Foo

Reputation: 363527

Judging from the traceback, it seems like you've done from scipy.sparse import * or something similar, so that numpy.hstack is shadowed by scipy.sparse.hstack. numpy.hstack works fine:

>>> 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]])

Upvotes: 12

Related Questions