NumPy:连接时出错 - 零维数组无法连接

时间:2016-04-05 01:54:29

标签: python numpy

我试图通过np.concat()方法连接两个有效的数组。

我的代码:

print X_train.shape, train_names.shape
X_train = np.concatenate([train_names,X_train], axis=0)

输出:

(3545, 93355) (3545, 692)


ValueError                                Traceback (most recent call last)
<ipython-input-58-59dc66874663> in <module>()
  1 print X_train.shape, train_names.shape
----> 2 X_train = np.concatenate([train_names,X_train], axis=0)


ValueError: zero-dimensional arrays cannot be concatenated

正如你所看到的,数组的形状对齐,我仍然得到这个奇怪的错误。为什么呢?

编辑:我也试过了axis=1。结果相同 编辑2:使用.astype(np.float64)的Eqauted数据类型。结果相同。

3 个答案:

答案 0 :(得分:13)

np.concatenate应用于scipy sparse矩阵会产生此错误:

In [162]: from scipy import sparse
In [163]: x=sparse.eye(3)
In [164]: x
Out[164]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements (1 diagonals) in DIAgonal format>
In [165]: np.concatenate((x,x))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-165-0b67d0029ca6> in <module>()
----> 1 np.concatenate((x,x))

ValueError: zero-dimensional arrays cannot be concatenated

sparse个函数可以执行此操作:

In [168]: sparse.hstack((x,x)).A
Out[168]: 
array([[ 1.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  1.]])
In [169]: sparse.vstack((x,x)).A
Out[169]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

答案 1 :(得分:1)

在我的情况下,问题是由于LabelEncoder()返回的矩阵的稀疏性质

所以这行给我一个错误:

np.append(airlineTrain, train_transformed,axis =1)

要修复它,我用了这个:

np.append(airlineTrain.toarray(), train_transformed.toarray(),axis =1 )

或者,您可能正在使用NLTK,其中可以使用todense()

来转换矩阵的稀疏存储

答案 2 :(得分:0)

将数组作为元组而不是列表传递。 X_train = np.concatenate((train_names,X_train), axis=0)

相关问题