You can create a mask over the elements in a that are within the given ranges and use this mask whenever you need to operate on a. If you want the encapsulate the mask and array in one entity, have a look at the numpy.ma module.
a = np.array([[[0,1,2],[3,4,5]],
[[6,7,8],[9,10,11]]])
b = np.array([[1,2],
[0,0]])
mask = np.arange(3)[None,None,:] <= b[:,:,None]
a[mask]
Output:
array([0, 1, 3, 4, 5, 6, 9])
But if you want the output as a non-homogeneous array, I cannot think of a better way to do that than using loops.
Answer from Kevin on Stack OverflowHow do I broadcast/slice by reference several indices for numpy arrays?
Slicing arrays with a Colon via PythonCall
Support for Multidimensional Slicing (Numpy Issue)
slice - How slicing in Python works - Stack Overflow
import numpy as np q = np.reshape(np.arange(9), (3,3)) w0 = q[..., 0] print(w0) #[0 3 6] w0[...] = -1 print((q[..., 0] == (-1)*np.ones(3)).all()) #True as expected w12 = q[..., [1,2]] print(w12) #[[1 2] [3 5] [7 8]] w12[...] = 0 print((q[..., [1,2]] == np.zeros((3,2))).all()) #False, not expected print(q) #[[-1 1 2] [-1 3 5] [-1 7 8]]
q is a 3x3 array, w0 represents its first column and accesses q by reference. w12 represents q's second and third columns but is defined by copy. How can I broadcast/slice q in such a way that manipulating w12 manipulates q, too?
Hi, I'm trying to create a simple game of life and I have problems putting zeros on the edge of my grid. When i try the following code i get an error and I don't understand why.
the variable grid represent a 2D array.
the code:
grid[0,:] = np.zeros_like(grid[0,:])#top_row
grid[-1,:] = np.zeros_like(grid[-1,:])#bottom_row
grid[:,0] = np.zeros_like(grid[:,0])#left
grid[:,-1] = np.zeros_like(grid[:,-1])#right
the error:
TypeError: list indices must be integers or slices, not tuple
