Sure! Let's look at a simple example using a 2D NumPy array to illustrate how axis=-1 works.
import numpy as np
# Create a 2D array (3 rows and 2 columns)
array = np.array([[1, 2],
[3, 4],
[5, 6]])
# Print the original array
print("Original Array:")
print(array)
# Sum along axis=-1 (which is the same as axis=1)
sum_axis_minus1 = np.sum(array, axis=-1)
# Print the result
print("\nSum along axis=-1:")
print(sum_axis_minus1)
Explanation:
-
Original Array:
[[1, 2], [3, 4], [5, 6]] -
Sum along
axis=-1:- When we sum along
axis=-1, we are summing across the columns for each row. - For the first row:
1 + 2 = 3 - For the second row:
3 + 4 = 7 - For the third row:
5 + 6 = 11
- When we sum along
-
Result:
[ 3, 7, 11]
So, the output of sum_axis_minus1 will be [3, 7, 11], which represents the sum of each row in the original array.
