连接两个Numpy矩阵 [英] joining two numpy matrices

查看:233
本文介绍了连接两个Numpy矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,使用以下矩阵:

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

我尝试过hstack但收到错误消息:

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

推荐答案

从回溯来看,您似乎已经完成了from scipy.sparse import *或类似的工作,因此numpy.hstackscipy.sparse.hstack遮盖了. numpy.hstack正常工作:

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

这篇关于连接两个Numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆