Numpy: subscribing outermost dimension in multidimensional array

3430 views python
8

I am working with multiple multidimensional arrays. Let us consider dummy example for simplicity:

 array_list=[np.ones(3), np.ones((3,3,3)), np.ones((3,3)), np.ones(3)]

I need to subscribe the outermost dimension of each array in the list. For example, my goal is to set some of the elements to zero according to a specified range in the outermost dimension:

array_list[0][0:2]=0
array_list[1][:,:,0:2]=0
array_list[2][:,0:2]=0
array_list[3][0:2]=0

In my real application I don't know how many arrays I have and how many dimensions are in there.

I would like to do the task in a for loop:

for array in array_list:
    array[???]=0

But I am struggling how to implement this if I don't know the dimensionality of each array.

answered question

1 Answer

10

Use the Ellipsis to select all dimensions except the last (if there's only 1, nothing is selected).

for array in array_list:
    array[..., 0:2] = 0

posted this

Have an answer?

JD

Please login first before posting an answer.