Python numpy array sum over certain indices
The accepted a[indices].sum()
approach copies data and creates a new array, which might cause problem if the array is large. np.sum
actually has an argument to mask out colums, you can just do
np.sum(a, where=[True, False, True, False])
Which doesn't copy any data.
The mask array can be obtained by:
mask = np.full(4, False)
mask[np.array([0,2])] = True
You can use sum
directly after indexing with indices
:
a = np.array([1,2,3,4])
indices = [0, 2]
a[indices].sum()