首页 > 解决方案 > Python numpy 在给定位置将二维数组插入更大的二维数组

问题描述

假设你有一个 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]
])

您现在想big用 的值覆盖 的某些值,从->small的左上角开始,位于 中的起点。smallsmall[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 函数,但找不到。

标签: pythonarraysnumpymultidimensional-arrayinsertion

解决方案


去做这个,

  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

推荐阅读