[英]Python numpy insert 2d array into bigger 2d array on given posiiton
Lets say you have a Numpy 2d-array:假设您有一个 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.]])
Another 2d array, smaller or equal in length on both axis:另一个二维数组,在两个轴上的长度更小或相等:
small = np.array([
[1, 2],
[3, 4]
])
You now want to override some values of big
with the values of small
, starting with the upper left corner of small
-> small[0][0]
on a starting point in big
.您现在想用 small 的值覆盖big
的一些值,从small
的左上角开始 -> small
small[0][0]
的起点为big
。
eg:例如:
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.]])
I expected an numpy function for that but couldn't find one.我期待一个 numpy function ,但找不到。
To do this,去做这个,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.