In higher-dimensional arrays, the concept of axes extends similarly, where each axis corresponds to a different dimension of the array. Here's how it works:
-
Understanding Axes:
- For a 3D array,
axis=0refers to the first dimension (depth),axis=1refers to the second dimension (rows), andaxis=2refers to the third dimension (columns). - For a 4D array,
axis=0would still refer to the first dimension, and so on.
- For a 3D array,
-
Example with a 3D Array:
Let's consider a 3D array and see howaxis=0,axis=1, andaxis=2work.
import numpy as np
# Create a 3D array (2 depth, 3 rows, 2 columns)
array_3d = np.array([[[1, 2],
[3, 4],
[5, 6]],
[[7, 8],
[9, 10],
[11, 12]]])
# Print the original 3D array
print("Original 3D Array:")
print(array_3d)
# Sum along axis=0
sum_axis_0 = np.sum(array_3d, axis=0)
print("\nSum along axis=0 (summing depth):")
print(sum_axis_0)
# Sum along axis=1
sum_axis_1 = np.sum(array_3d, axis=1)
print("\nSum along axis=1 (summing rows):")
print(sum_axis_1)
# Sum along axis=2
sum_axis_2 = np.sum(array_3d, axis=2)
print("\nSum along axis=2 (summing columns):")
print(sum_axis_2)
Explanation of Results:
-
Original 3D Array:
[[[ 1, 2], [ 3, 4], [ 5, 6]], [[ 7, 8], [ 9, 10], [11, 12]]] -
Sum along
axis=0:- This sums across the depth (the first dimension).
- Result:
[[ 8, 10], [12, 14], [16, 18]](Each element is the sum of the corresponding elements from the two depth layers.)
-
Sum along
axis=1:- This sums across the rows for each depth layer.
- Result:
[[ 9, 12], [27, 30]](Each element is the sum of the rows within each depth layer.)
-
Sum along
axis=2:- This sums across the columns for each row in each depth layer.
- Result:
[[ 3, 7, 11], [15, 18]](Each element is the sum of the columns within each row of each depth layer.)
Summary:
- The concept of axes in higher-dimensional arrays allows you to specify which dimension you want to perform operations on.
axis=0refers to the first dimension (depth),axis=1refers to the second dimension (rows), andaxis=2refers to the third dimension (columns).- This flexibility is crucial for manipulating and analyzing multi-dimensional data effectively.
