简体   繁体   English

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

[英]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,去做这个,

  1. Make sure the position will not make the small matrix exceed the boundaries of the big matrix确保 position 不会使小矩阵超出大矩阵的边界
  2. Just subset the part of the big matrix at the position with the small matrix.只需将 position 的大矩阵部分与小矩阵子集即可。
 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM