joining two numpy matrices

孤街醉人 提交于 2020-01-02 03:44:06

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/12246680/joining-two-numpy-matrices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!