Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of numpy array based on elements in another numpy array?

I have 2 arrays:

arr1 =np.array([10, 20, 15, 0, 45, 100])
arr2 =np.array([0,   3,  1, 6,  0,   0])

I want to get the sum of those elements from arr1 whose corresponding entries in arr2 are 0. The sum would be 10+45+100=155 in the example. How can I achieve this easily?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a boolean mask for arr2 where the elements are equal to 0 and then use this mask to select the corresponding elements from arr1. Finally, you can calculate the sum of the selected elements.

import numpy as np
arr1 = np.array([10, 20, 15, 0, 45, 100])
arr2 = np.array([0, 3, 1, 6, 0, 0])
mask = arr2 == 0  
result = np.sum(arr1[mask]) 
print(result) 

Output:

155
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading