Python numpy 在给定位置将二维数组插入更大的二维数组

标签 python arrays numpy multidimensional-array insertion

假设您有一个 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 函数,但找不到。

最佳答案

为此,

  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 + to_insert_arr.shape[0]
    y2 = y1 + to_insert_arr.shape[1]

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

    big_arr[x1:x2, y1:y2] = to_insert_arr

    return big_arr


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

关于Python numpy 在给定位置将二维数组插入更大的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66896138/

相关文章:

Python 3.3 - 从规则间隔的顶点创建 3D 网格作为 Wavefront obj 文件

python - 是否可以对 NumPy 数组的递归计算进行矢量化,其中每个元素都依赖于前一个元素?

java - ArithmeticException 除以零...如何修复此方法?

java - 用户输入int到Array然后使用冒泡排序对数字进行排序

python - 将 NumPy 数组转换为 Python 列表

python - 快速比较 numpy 数组元素,大于或小于彼此

python - 广度优先搜索 - 标准 Python 库

c++ - 使用 python 正则表达式从 C++ 源中提取命名空间

javascript - 使用 lodash 将对象转换为数组

python - 在 PyInstaller 中,为什么 NumPy.Random.Common 不能作为模块加载?