【发布时间】:2023-03-24 02:15:01
【问题描述】:
我有一个多维 numpy 数组,其中元素是 True 或 False 值:
import numpy as np
#just making a toy array grid to show what I want to do
grid = np.ones((4,4),dtype = 'bool')
grid[0,0]=False
grid[-1,-1]=False
#now grid has a few false values but is a 4x4 filled with mostly true values
现在我需要生成另一个数组 M,其中每个站点 M[i,j] 的值取决于 grid[i:i+2,j:j+2],如下所示
M = np.empty((4x4)) #elements to be filled
#here is the part I want to clean up
for ii in range(4):
for jj in range(4):
#details here are unimportant. It's just that M[ii,jj] depends on
#multiple elements of grid in some way
if ii+2<=4 and jj+2<=4:
M[ii,jj] = np.all(grid[ii:ii+2,jj:jj+2]==True)
else:
M[ii,jj] = False
有没有办法使用网格中的元素填充数组 M 而没有双循环?
【问题讨论】:
标签: python numpy multidimensional-array vectorization