【问题标题】:Expanding NumPy array over extra dimension在额外维度上扩展 NumPy 数组
【发布时间】:2013-07-08 22:57:49
【问题描述】:

在额外维度上扩展给定 NumPy 数组的最简单方法是什么?

例如,假设我有

>>> np.arange(4)
array([0, 1, 2, 3])
>>> _.shape
(4,)
>>> expand(np.arange(4), 0, 6)
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])
>>> _.shape
(6, 4)

或者这个,稍微复杂一点:

>>> np.eye(2)
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> _.shape
(2, 2)
>>> expand(np.eye(2), 0, 3)
array([[[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]]])
>>> _.shape
(3, 2, 2)

【问题讨论】:

  • 你试过熊猫吗?
  • 不,我没有,可能对我想要的东西来说太过分了。

标签: python numpy


【解决方案1】:

我会推荐np.tile

>>> a=np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> np.tile(a,(6,1))
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])

>>> b= np.eye(2)
>>> b
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> np.tile(b,(3,1,1))
array([[[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]]])

在多个维度上扩展也很容易:

>>> np.tile(b,(2,2,2))
array([[[ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.]],

       [[ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.]]])

【讨论】:

  • "通过重复 A 的次数来构造一个数组,次数由 reps 给出。"是的,正是,谢谢!
  • 如果我理解正确,这会创建一个新的数组,无用地占用大量内存,而现有数组的简单 view 就足够了......
【解决方案2】:

我认为修改数组的步长可以很容易地编写expand

def expand(arr, axis, length):
    new_shape = list(arr.shape)
    new_shape.insert(axis, length)
    new_strides = list(arr.strides)
    new_strides.insert(axis, 0)
    return np.lib.stride_tricks.as_strided(arr, new_shape, new_strides)

函数返回原始数组的视图,不占用额外内存。

与新轴对应的stride 为 0,因此无论该轴值的索引如何,都保持不变,基本上为您提供所需的行为。

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2021-02-16
    • 2023-03-23
    • 2023-03-07
    • 2021-06-26
    相关资源
    最近更新 更多