Numpy 如何插入在NP数组中间的值替换
我有一个大小为200x200的np零数组。我想把中间的16x16块0变成1。我该怎么做 这是我的起始数组Numpy 如何插入在NP数组中间的值替换,numpy,Numpy,我有一个大小为200x200的np零数组。我想把中间的16x16块0变成1。我该怎么做 这是我的起始数组 cells=np.zero((200200),dtype=int) 形状 (200200) 我希望中间的16x16个零是1。这里有一个更灵活的方法: def slice_center(arr, n): center = arr.shape[0] // 2 target = n // 2 return center - target, center + target
cells=np.zero((200200),dtype=int)
形状
(200200)
我希望中间的16x16个零是1。这里有一个更灵活的方法:
def slice_center(arr, n):
center = arr.shape[0] // 2
target = n // 2
return center - target, center + target
i, j = slice_center(arr, 16)
arr[i:j, i:j] = 1
你可以计算中间部分的指数,在这个特殊的例子中,它是从92到108
>>> cells[92:108,92:108]
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])