/Curriculum/Core NumPyStatistics & Reductions

19. NumPy Axis OperationsIntermediate

Master the Golden Axis Rule: axis=0 collapses rows (↓); axis=1 collapses columns (→).

15 mins

Concept Overview

The `axis` parameter defines which dimension to collapse during multi-dimensional aggregations. In 2D: `axis=0` moves vertically DOWN across rows; `axis=1` moves horizontally ACROSS columns.

Hardware Mental Model

The Golden Axis Rule: 'The axis you specify is the axis that disappears!' If you specify axis=0 (rows), rows disappear leaving column totals.

Key Concepts (1)Click snippet to load in editor

`axis=0` collapses Dimension 0 (rows ↓), producing column results. `axis=1` collapses Dimension 1 (columns →), producing row results.

col_sums = matrix.sum(axis=0); row_sums = matrix.sum(axis=1)

Interactive 2D Axis Explorer

Toggle between axis=0 and axis=1 to see reduction direction
arr.sum(axis=0) → Collapses Rows (Down Columns ↓)Calculates the total for each vertical column.
Result Shape: (3,)
1
2
3
4
5
6
7
8
9
12
15
18
Calculation Breakdown:
Col 0: 1 + 4 + 7 = 12
Col 1: 2 + 5 + 8 = 15
Col 2: 3 + 6 + 9 = 18

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:row_sums = matrix.sum(axis=0) # Intending row sums but got column sums!
✓ Correct:row_sums = matrix.sum(axis=1)

Remember: axis=0 acts along rows (downward), aggregating into column sums.

Pro Tip: To get 1 value per student/row, use `axis=1`.

📌 Quick Revision

Core takeaway points from this topic
`axis=0`: Traverses vertically down rows (produces column totals).
`axis=1`: Traverses horizontally across columns (produces row totals).
`axis=None`: Collapses all dimensions into a single scalar.
`keepdims=True`: Preserves original number of dimensions as singletons.
Editor: 19. NumPy Axis Operations
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Compute Column Sums (axis=0)

Given `mat = np.array([[10, 20], [30, 40]])`, compute column sums with `mat.sum(axis=0)` and print.

Expected Output Target:[40 60]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state