NumPy array sum based on indices

In this post, we are going to learn how to Sum NumPy array elements based on indices, the numpy library sum() function is used to sum numpy array elements. First, we have to install and import into our code.

1.NumPy array Sum based on list of indices


Sometimes we have indices of numpy array as list and need to find the sum-based list of indices. In this python program, We have found the sum of numy array elements based on a given list of indices.

import numpy as np
nparr= np.array([[1, 2, 3, 4, 5],  
              [6, 7, 8, 9, 10], 
              [11, 12, 13, 14, 15,]])

indices = [0, 2]
 
columnSum = nparr[indices].sum()
print('\nnumpy array sum based on list of indices:',columnSum)

Output

numpy array sum based on list of indices: 80

2. NumPy array sum based on indices


In this Python program, we will understand how to find the SUM of numpy array elements based on indices without using numpy library built-in function sum() by using python built-in sum() function.

import numpy as np
nparr= np.array([[1, 2, 3, 4, 5],  
              [6, 7, 8, 9, 10], 
              [11, 12, 13, 14, 15,]])

indices = [0, 2]
print('\nsum of numpy array based on indices:\n',sum(nparr[i] for i in indices))

Output

sum of numpy array based on indices:
 [12 14 16 18 20]

3. NumPy array sum based on indices


In this Python program, we are finding the sum of numpy array elements based on indices by using np.sum() function and passing the numpy array along with indices.

import numpy as np
nparr = np.array([[1, 2, 3, 4, 5],  
              [6, 7, 8, 9, 10], 
              [11, 12, 13, 14, 15,]])

indices = [0, 2]
print('\nsum of numpy array based on indices:\n',np.sum(nparr[indices]))

Output

sum of numpy array based on indices: 80

4. Numpy Sum based on a list of lists indices


In this Python program, we are finding numpy array elements sum based on a list of lists of indices along with axis=0.

import numpy as np
nparr = np.array([[1, 2, 3, 4, 5],  
              [6, 7, 8, 9, 10], 
              [11, 12, 13, 14, 15,]])

indices = [[0, 0],[0, 1]]

print('\nsum of numpy array based on indices:\n',nparr[(indices)].sum(axis = 0))

Output

sum of numpy array based on indices: 3