Skip to main content

Numpy: Accessing sub ndarrays with multiple index lists

I am trying to access (more precisely: add to) a subset of a numpy array using multiple index lists. However, what is working perfectly with slices, does not work as expected using arbitrary index lists:

import numpy as np

# this one works:

A_4th_order = np.zeros( (4,2,4,2) )

sub_a = np.ones( (3,1,3,1) )

i = k = slice(0,3)
j = l = slice(1,2)

A_4th_order[i,j,k,l] += sub_a


# this one doesn't:

B_4th_order = np.zeros( (4,2,4,2) )

sub_b = np.ones( (3,1,3,1) )

i = k = np.array([0,1,2], dtype=int)
j = l = np.array([1], dtype=int)

B_4th_order[i,j,k,l] += sub_b

How can I achieve this operation in an efficient and readable manner?



source https://stackoverflow.com/questions/77793897/numpy-accessing-sub-ndarrays-with-multiple-index-lists

Comments