发布附加不同形状的ndarray的问题

时间:2018-04-26 06:39:16

标签: numpy numpy-ndarray

我有一个numpy ndarray形状(25,2),我试图追加一个有形状的值(2,)。

我尝试过使用append方法,但到目前为止还没有运气。

有什么想法? 谢谢!

2 个答案:

答案 0 :(得分:1)

要以这种方式附加工作,您需要满足documentation中指定的两个条件。

  1. 附加对象必须具有相同的尺寸。它的形状应为(1, 2)
  2. 您必须指定要连接的轴,否则numpy会使数组变平。
  3. 例如:

    import numpy
    x = numpy.ones((3, 2))
    y = [[1, 2]]
    numpy.append(x, y, axis=0)
    

    结果:

    array([[ 1.,  1.],
           [ 1.,  1.],
           [ 1.,  1.],
           [ 1.,  2.]])
    

答案 1 :(得分:0)

append method您遇到了哪些错误? “没有运气”就像“没有工作”一样糟糕。在正确的问题中,您应该显示预期值和错误。然而,这个话题经常出现,我们可以做出很好的猜测。

In [336]: a = np.ones((3,2),int)
In [337]: b = np.zeros((2,),int)

但首先我会迂腐并尝试append method

In [338]: a.append(b)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-338-d6231792f85d> in <module>()
----> 1 a.append(b)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

lists有一个追加方法; numpy数组没有。

有一个命名不佳的append函数:

In [339]: np.append(a,b)
Out[339]: array([1, 1, 1, 1, 1, 1, 0, 0])
In [340]: _.reshape(-1,2)
Out[340]: 
array([[1, 1],
       [1, 1],
       [1, 1],
       [0, 0]])

这在某种程度上有效。但是,如果我阅读文档,并提供轴参数:

In [341]: np.append(a,b, axis=0)
...
-> 5166     return concatenate((arr, values), axis=axis)
ValueError: all the input arrays must have same number of dimensions

现在只需调用np.concatenate,将2个参数转换为列表。

如果这是您得到的错误,并且不理解,您可能需要查看有关尺寸和形状的基本numpy文档。

a为2d,b为1d。要连接,我们需要重新整形b,使其为(1,2),这是一种与a的(3,2)兼容的形状。有几种方法可以做到这一点:

In [342]: np.concatenate((a, b.reshape(1,2)), axis=0)
Out[342]: 
array([[1, 1],
       [1, 1],
       [1, 1],
       [0, 0]])

远离np.append;它对许多初学者来说太混乱了,并没有为基础concatenate添加任何重要的东西。