Python numpy 在给定位置将二维数组插入更大的二维数组
Python numpy insert 2d array into bigger 2d array on given posiiton
假设您有一个 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 函数,但找不到。
为此,
- 确保位置不会使小矩阵超出大矩阵的边界
- 把大矩阵的部分在小矩阵的位置进行子集
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
假设您有一个 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 函数,但找不到。
为此,
- 确保位置不会使小矩阵超出大矩阵的边界
- 把大矩阵的部分在小矩阵的位置进行子集
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