What will be the output of the following code?
import numpy as np
arr = np.arange(1, 10).reshape(3, 3)
result = arr.sum(axis=0) - arr.sum(axis=1)
print(result)
[0, 0, 0]
[1, -1, 1]
[3, -3, 3]
[2, 2, -2]
Step 1: Create the array with np.arange(1, 10)
The function np.arange(1, 10) creates a 1D NumPy array containing integers from 1 to 9 (inclusive of 1 but exclusive of 10).
Step 2: Reshape the array to 3x3
The method .reshape(3, 3) converts the 1D array into a 2D array with 3 rows and 3 columns:
Step 3: Compute arr.sum(axis=0)
The parameter axis=0 means sum along columns (vertically).
For each column, we add the elements from the top to the bottom:
- First column:
- Second column:
- Third column:
Result of arr.sum(axis=0):
Step 4: Compute arr.sum(axis=1)
The parameter axis=1 means sum along rows (horizontally).
For each row, we add the elements from left to right:
- First row:
- Second row:
- Third row:
Result of arr.sum(axis=1):
Step 5: Perform element-wise subtraction
The subtraction operation is element-wise, meaning corresponding elements of the two arrays are subtracted.
Result of arr.sum(axis=0) - arr.sum(axis=1):
Step 6: Print the result
Finally, the result is printed:
Key Points:
- axis=0 computes the sum along columns (vertically).
- axis=1 computes the sum along rows (horizontally).
- Subtraction is performed element-wise between the two resulting arrays.
0 Comments:
Post a Comment