假设您有一个 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 + 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/