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?
>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