How does this apply to higher-dimensional arrays?

QuestionsQuestions8 SkillsProNumPy BroadcastingOct, 10 2025
086

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:

  1. Understanding Axes:

    • For a 3D array, axis=0 refers to the first dimension (depth), axis=1 refers to the second dimension (rows), and axis=2 refers to the third dimension (columns).
    • For a 4D array, axis=0 would still refer to the first dimension, and so on.
  2. Example with a 3D Array:
    Let's consider a 3D array and see how axis=0, axis=1, and axis=2 work.

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:

  1. Original 3D Array:

    [[[ 1,  2],
      [ 3,  4],
      [ 5,  6]],
    
     [[ 7,  8],
      [ 9, 10],
      [11, 12]]]
  2. 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.)

  3. 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.)

  4. 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=0 refers to the first dimension (depth), axis=1 refers to the second dimension (rows), and axis=2 refers to the third dimension (columns).
  • This flexibility is crucial for manipulating and analyzing multi-dimensional data effectively.

0 Comments

no data
Be the first to share your comment!