I have a 2D numpy array.
x = np.arange(25).reshape(5, 5)
I need to create a mask by index condition. For example elements with even indexes.
mask = np.zeros((5, 5), dtype=bool)
for i in range(5):
for j in range(5):
if i % 2 == 0 and j % 2 == 0:
mask[i][j] = True
Is there a way to create such a mask using numpy tools?
CodePudding user response:
Replace your nested loops with this:
mask[::2,::2] = True
The ::2
means "from beginning to end, for every second element" in each axis.