Using axis=0 in NumPy operations differs from axis=-1 in that it refers to the first axis of the array, which is the rows in a 2D array. Let's illustrate this with an example:
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=0
sum_axis_0 = np.sum(array, axis=0)
# Print the result
print("\nSum along axis=0:")
print(sum_axis_0)
Explanation:
-
Original Array:
[[1, 2], [3, 4], [5, 6]] -
Sum along
axis=0:- When we sum along
axis=0, we are summing down the rows for each column. - For the first column:
1 + 3 + 5 = 9 - For the second column:
2 + 4 + 6 = 12
- When we sum along
-
Result:
[ 9, 12]
Summary of Differences:
axis=-1: Sums across the last dimension (columns in a 2D array), resulting in a sum for each row.axis=0: Sums down the first dimension (rows in a 2D array), resulting in a sum for each column.
So, the output of sum_axis_0 will be [9, 12], which represents the sum of each column in the original array.
