Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 733
Zach Avatar asked Sep 03 '12 11:09

Zach


1 Answers

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]])
like image 127
Fred Foo Avatar answered Nov 14 '22 22:11

Fred Foo