【问题标题】:How to assign smaller array to larger in overlapping area如何将较小的数组分配给较大的重叠区域
【发布时间】:2020-09-08 14:34:36
【问题描述】:

我正在尝试将一个小的 8x7 2D 数组放入 8x8 2D 数组中。

这是我正在使用的:

--> Array called 'a' with shape 8x7

a = [[ 16.,  11.,  10.,  16.,  24.,  40.,  51.],
     [ 12.,  12.,  14.,  19.,  26.,  58.,  60.],
     [ 14.,  13.,  16.,  24.,  40.,  57.,  69.],
     [ 14.,  17.,  22.,  29.,  51.,  87.,  80.],
     [ 18.,  22.,  37.,  56.,  68., 109., 103.],
     [ 24.,  35.,  55.,  64.,  81., 104., 113.],
     [ 49.,  64.,  78.,  87., 103., 121., 120.],
     [ 72.,  92.,  95.,  98., 112., 100., 103.]]


--> Array called 'b' with shape 8x8

b = [[0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.]]

所以基本上,我想要的是:

--> Array called 'c' with shape 8x8

c = [[ 16.,  11.,  10.,  16.,  24.,  40.,  51., 0],
     [ 12.,  12.,  14.,  19.,  26.,  58.,  60., 0],
     [ 14.,  13.,  16.,  24.,  40.,  57.,  69., 0],
     [ 14.,  17.,  22.,  29.,  51.,  87.,  80., 0],
     [ 18.,  22.,  37.,  56.,  68., 109., 103., 0],
     [ 24.,  35.,  55.,  64.,  81., 104., 113., 0],
     [ 49.,  64.,  78.,  87., 103., 121., 120., 0],
     [ 72.,  92.,  95.,  98., 112., 100., 103., 0]]

有没有一种简单的方法可以做到这一点,最好不使用循环,例如 'for' 、 'while' 、 'map' 还是列表理解?

提前谢谢你!

【问题讨论】:

    标签: python arrays numpy indexing numpy-ndarray


    【解决方案1】:

    您可以将分配给b 的切片分配到a 的维度:

    x, y = a.shape
    b[:x, :y] = a
    

    print(b)
    array([[ 16.,  11.,  10.,  16.,  24.,  40.,  51.,   0.],
           [ 12.,  12.,  14.,  19.,  26.,  58.,  60.,   0.],
           [ 14.,  13.,  16.,  24.,  40.,  57.,  69.,   0.],
           [ 14.,  17.,  22.,  29.,  51.,  87.,  80.,   0.],
           [ 18.,  22.,  37.,  56.,  68., 109., 103.,   0.],
           [ 24.,  35.,  55.,  64.,  81., 104., 113.,   0.],
           [ 49.,  64.,  78.,  87., 103., 121., 120.,   0.],
           [ 72.,  92.,  95.,  98., 112., 100., 103.,   0.]])
    

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多