Code Explanation:
1. Importing the NumPy library
import numpy as np
This line imports the NumPy library, giving it the alias np, which is a standard practice.
NumPy provides powerful support for numerical operations and handling arrays efficiently.
2. Creating a NumPy array
arr = np.array([3, 15, 8, 22, 7])
This creates a NumPy array named arr with the elements [3, 15, 8, 22, 7].
The array holds 5 integers.
3. Creating a boolean mask
mask = arr < 10
This line creates a boolean mask based on the condition arr < 10.
It checks each element in arr and returns True if the element is less than 10, otherwise False.
The result of this comparison is:
[True, False, True, False, True]
4. Using the mask to modify the array
arr[mask] = 0
This line uses the mask to update the array arr.
Wherever the mask is True, the corresponding element in arr is replaced with 0.
The elements at indices 0, 2, and 4 are replaced (i.e., 3, 8, and 7).
Updated arr becomes:
[0, 15, 0, 22, 0]
5. Calculating and printing the sum of the array
print(np.sum(arr))
np.sum(arr) computes the sum of all elements in the updated array:
0 + 15 + 0 + 22 + 0 = 37
The result 37 is printed to the console.
Final Output:
37
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment