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

标签 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) 等式数据类型。相同的结果。

最佳答案

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

关于python - NumPy:连接时出错 - 无法连接零维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415811/

相关文章:

python - 优化Python : Large arrays,内存问题

python - 从 python 中的 groupby 对象中选择特定行

python - 如何使列表中的变量可识别为数字?

python - 可逆字典到数组映射

python - 使用 numpy.searchsorted 后查找未排序的索引

numpy - 赛通错误 : Undeclared name not built in:array

python - 在中间件中通过 set_urlconf 和 request.urlconf 修改 Django urlconf 是否安全?

python - 如何为 pip 设置默认的 python 版本?

python - 在 Bokeh 中重画曼德尔布罗特?

python - 划分数组时 numpy 中的意外行为