【问题标题】:Python numpy insert 2d array into bigger 2d array on given posiitonPython numpy 在给定位置将二维数组插入更大的二维数组
【发布时间】:2021-06-27 22:58:32
【问题描述】:

假设你有一个 Numpy 二维数组:

import numpy as np
big = np.zeros((4, 4))
>>> big
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
   

另一个二维数组,两个轴上的长度小于或等于:

small = np.array([
    [1, 2],
    [3, 4]
])

您现在想用small 的值覆盖big 的某些值,从small 的左上角开始-> small[0][0] 的起点在big

例如:

import numpy as np

big = np.zeros((4, 4))

small = np.array([
    [1, 2],
    [3, 4]
])

def insert_at(big_arr, pos, to_insert_arr):
    return [...]


result = insert_at(big, (1, 2), small)
>>> result
array([[0., 0., 0., 0.],
       [0., 0., 1., 2.],
       [0., 0., 3., 4.],
       [0., 0., 0., 0.]])

我希望有一个 numpy 函数,但找不到。

【问题讨论】:

  • 为什么不将小数组分配给大数组中的等效切片呢?如果要在 (i, j) 处插入 small,则 big[i : i + #rows_ in_small, j : j + #column_in_small] = small。

标签: python arrays numpy multidimensional-array insertion


【解决方案1】:

为此,

  1. 确保位置不会使小矩阵超出大矩阵的边界
  2. 只需将大矩阵在小矩阵位置的部分子集即可。
import numpy as np

big = np.zeros((4, 4))

small = np.array([
    [1, 2],
    [3, 4]
])

def insert_at(big_arr, pos, to_insert_arr):
    x1 = pos[0]
    y1 = pos[1]
    x2 = x1 + small.shape[0]
    y2 = y1 + small.shape[1]

    assert x2  <= big.shape[0], "the position will make the small matrix exceed the boundaries at x"
    assert y2  <= big.shape[1], "the position will make the small matrix exceed the boundaries at y"

    big[x1:x2,y1:y2] = small

    return big
    


result = insert_at(big, (1, 2), small)
result

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2017-01-26
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多