numpy合并矩阵操作ValueError: all the input arrays must have same number of dimensions

时间:2022-05-23 02:11:10

当使用numpy对稀疏矩阵进行合并时出现异常(对于密集(dense)矩阵没有问题)

ValueError: all the input arrays must have same number of dimensions

操作涉及到np.hstack((m1,m2)),np.column_stack((m1,m2)),np.concatenate([m1, m2], axis=1)等

解决方案来源于:http://www.it1352.com/239795.html

m1 = sparse.rand(10, 10000)
m2 = np.random.random((10, 1))
print 'm1 shape:', m1.shape
print 'm2 shape:', m2.shape
print 'Stacked shape:', np.hstack((m1,m2)).shape

异常出现

解决方案:

    X = sparse.rand(10, 10000)
    xt = np.random.random((10, 1))
    res = sparse.hstack((X,xt)).toarray()
    print('X shape:', X.shape)
    print('xt shape:', xt.shape)
    print('Stacked shape:', res.shape)