How does axis=0 differ?

QuestionsQuestions8 SkillsProNumPy BroadcastingOct, 10 2025
0115

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:

  1. Original Array:

    [[1, 2],
     [3, 4],
     [5, 6]]
  2. 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
  3. 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.

0 Comments

no data
Be the first to share your comment!