【问题标题】:Numpy append 3D vectors without flattening [duplicate]Numpy附加3D向量而不展平[重复]
【发布时间】:2018-08-01 11:07:01
【问题描述】:

我有以下向量

video_132.shape
Out[64]: (64, 3)

我会添加一个包含三个值的新 3D 向量

video_146[1][146][45]

这样

video_146[1][146][45].shape
Out[68]: (3,)

video_146[1][146][45]
Out[69]: array([217, 207, 198], dtype=uint8)

当我执行以下操作时

np.append(video_132,video_146[1][146][45])

我应该得到

video_132.shape
Out[64]: (65, 3) # originally (64,3)

但是我得到:

Out[67]: (195,) # 64*3+3=195

好像把向量变平了

如何通过保留 3D 结构来进行追加?

【问题讨论】:

  • 查看 !append` 的代码。当您不指定轴时,它会使输入变平。它让太多用户感到困惑。避免它。

标签: python-3.x numpy append


【解决方案1】:

为了简单起见,让我们重命名 video_132 --> avideo_146[1][146][45] --> b。特定的值并不重要,所以让我们说

In [82]: a = np.zeros((64, 3))
In [83]: b = np.ones((3,))

然后我们可以将b 附加到a 使用:

In [84]: np.concatenate([a, b[None, :]]).shape
Out[84]: (65, 3)

由于np.concatenate 返回一个新数组,将其返回值重新分配给a 以“追加”ba

a = np.concatenate([a, b[None, :]])

【讨论】:

    【解决方案2】:

    append 的代码:

    def append(arr, values, axis=None):
        arr = asanyarray(arr)
        if axis is None:
            if arr.ndim != 1:
                arr = arr.ravel()
            values = ravel(values)
            axis = arr.ndim-1
        return concatenate((arr, values), axis=axis)
    

    如果没有提供轴,请注意 arrraveled

    In [57]: np.append(np.ones((2,3)),2)
    Out[57]: array([1., 1., 1., 1., 1., 1., 2.])
    

    append 真正针对的是简单的情况,例如向一维数组添加标量:

    In [58]: np.append(np.arange(3),6)
    Out[58]: array([0, 1, 2, 6])
    

    否则行为难以预测。

    concatenate 是基本操作(内置)并采用一个列表,而不仅仅是两个。所以我们可以在一个列表中收集许多数组(或列表)并在循环结束时执行一个concatenate。而且由于它不会事先调整尺寸,它迫使我们自己去做。

    因此,要将形状 (3,) 添加到 (64,3),我们将 (3,) 转换为 (1,3)。如果我们指定轴,append 需要与concatenate 相同的尺寸调整。

    In [68]: np.append(arr,b[None,:], axis=0).shape
    Out[68]: (65, 3)
    In [69]: np.concatenate([arr,b[None,:]], axis=0).shape
    Out[69]: (65, 3)
    

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 2019-01-11
      • 2017-12-17
      • 1970-01-01
      • 2021-08-08
      • 2012-10-13
      • 2018-11-05
      • 2015-03-31
      相关资源
      最近更新 更多