python - 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
的左上角开始,位于 中的起点。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 函数,但找不到。
解决方案
去做这个,
- 确保位置不会使小矩阵超出大矩阵的边界
- 只需在小矩阵的位置子集大矩阵的部分。
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
推荐阅读
- twig - Wordpress,Timber,Twig 模板中 WCK 自定义字段的打印字段
- asp.net - 在 asp.net 核心中间件中反序列化 HttpContext 上下文响应
- python-3.x - KeyError:尝试在字典中查找最小值时出现 411
- django - 在 Gitlab 上为 django 项目设置 CI/CD
- debugging - 一旦检查了一个值,Rstudio 调试器就会退出调试模式
- javascript - 应该显示错误消息的函数不显示它
- python-3.x - Python递归函数计数用户
- angular - 如果在搜索栏中未找到结果,则显示错误消息
- javascript - 无法从 SVG 图像元素加载图像
- java - 如何在 spring-boot 中管理 gRPC 服务器通道