Python numpy array sum over certain indices

Marcus_Ma picture Marcus_Ma · Dec 10, 2017 · Viewed 25.1k times · Source

How to perform a sum just for a list of indices over numpy array, e.g., if I have an array a = [1,2,3,4] and a list of indices to sum, indices = [0, 2] and I want a fast operation to give me the answer 4 because the value for summing value at index 0 and index 2 in a is 4

Answer

andrew_reece picture andrew_reece · Dec 10, 2017

You can use sum directly after indexing with indices:

a = np.array([1,2,3,4])
indices = [0, 2] 
a[indices].sum()