Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

Transpose and Axis Operations

Learn how to transpose NumPy arrays, exchange rows and columns, understand array axes, and perform calculations along specific dimensions. Explore transpose(), swapaxes(), moveaxis(), and axis-based aggregation with practical examples.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand the meaning of axes in NumPy arrays.
  • Transpose a two-dimensional array using transpose().
  • Use the .T attribute as a transpose shortcut.
  • Understand how array shapes change after transposition.
  • Use swapaxes() to exchange two axes.
  • Use moveaxis() to reposition an axis.
  • Perform sum, mean, and other operations along a specified axis.
  • Apply axis operations to multidimensional datasets.

2. Understanding Axes in NumPy

An axis represents a dimension of a NumPy array. The number of axes in an array is equal to its number of dimensions, which is returned by the ndim attribute.

In a two-dimensional array, axis 0 represents the row dimension and axis 1 represents the column dimension. Understanding these dimensions is important when selecting, aggregating, or rearranging array data.

import numpy as np data = np.array([ [10, 20, 30], [40, 50, 60] ]) print("Dimensions:", data.ndim) print("Shape:", data.shape)

Output:

Dimensions: 2 Shape: (2, 3)
2D NumPy Array 10 20 30 40 50 60 Row 0 Row 1 Axis 1: Columns → Axis 0 corresponds to the row dimension

For a two-dimensional array, axis 0 is the row dimension and axis 1 is the column dimension.

Remember: Axis numbers start from zero. A one-dimensional array has axis 0, while a two-dimensional array has axes 0 and 1.

3. What Is Transposing an Array?

Transposing an array changes the order of its axes. For a two-dimensional array, transposition exchanges the row and column dimensions. Rows become columns, and columns become rows.

The original values remain the same, but their positions in the resulting array change according to the new axis order.

import numpy as np data = np.array([ [10, 20, 30], [40, 50, 60] ]) transposed = data.transpose() print("Original shape:", data.shape) print("Transposed shape:", transposed.shape) print(transposed)

Output:

Original shape: (2, 3) Transposed shape: (3, 2) [[10 40] [20 50] [30 60]]
Original (2, 3) Transposed (3, 2) 10 20 30 40 50 60 10 40 20 50 30 60 Rows and columns exchange positions

Transposing a matrix with shape (2, 3) produces a matrix with shape (3, 2).

4. Using the transpose() Method

The transpose() method returns an array with its axes rearranged. For a two-dimensional array, calling transpose() without arguments reverses the axis order.

import numpy as np matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) result = matrix.transpose() print(result) print("Original:", matrix.shape) print("Result:", result.shape)

Output:

[[1 4] [2 5] [3 6]] Original: (2, 3) Result: (3, 2)

For arrays with more than two dimensions, you can specify the order in which axes should appear in the result.

import numpy as np data = np.zeros((2, 3, 4)) result = data.transpose(1, 0, 2) print("Original shape:", data.shape) print("New shape:", result.shape)

Output:

Original shape: (2, 3, 4) New shape: (3, 2, 4)
Tip: When supplying axis numbers to transpose(), each original axis must appear exactly once in the requested axis order.

5. Using the .T Attribute

NumPy provides the .T attribute as a convenient shortcut for transposing an array. It reverses the order of dimensions. For a two-dimensional matrix, this exchanges rows and columns.

import numpy as np matrix = np.array([ [11, 22, 33], [44, 55, 66] ]) print(matrix.T)

Output:

[[11 44] [22 55] [33 66]]

For one-dimensional arrays, .T does not convert a one-dimensional array into a column vector. Its shape remains unchanged.

import numpy as np values = np.array([10, 20, 30]) print(values.shape) # (3,) print(values.T.shape) # (3,)
Common mistake: If you need a two-dimensional column vector, use values.reshape(-1, 1) rather than relying on values.T.

6. Understanding Axis-Based Calculations

Many NumPy functions allow an axis argument. This argument specifies the dimension along which an operation is performed. For a two-dimensional array, axis 0 combines values vertically across rows, while axis 1 combines values horizontally across columns.

import numpy as np marks = np.array([ [70, 80, 90], [60, 85, 95] ]) print("Sum along axis 0:") print(marks.sum(axis=0)) print("Sum along axis 1:") print(marks.sum(axis=1))

Output:

Sum along axis 0: [130 165 185] Sum along axis 1: [240 240]
Operation Meaning Output Shape
marks.sum(axis=0) Add values down each column. (3,)
marks.sum(axis=1) Add values across each row. (2,)
marks.sum() Add every element in the array. Scalar result
Easy way to remember: In a two-dimensional array, axis=0 reduces the row dimension, while axis=1 reduces the column dimension.

7. Using mean() with an Axis

The mean() function calculates averages. With an axis argument, it calculates separate averages for each row or column instead of calculating one average for the entire array.

import numpy as np marks = np.array([ [70, 80, 90], [60, 85, 95] ]) column_averages = marks.mean(axis=0) row_averages = marks.mean(axis=1) print("Column averages:", column_averages) print("Row averages:", row_averages) print("Overall average:", marks.mean())

Output:

Column averages: [65. 82.5 92.5] Row averages: [80. 80. ] Overall average: 80.0

Column averages combine the marks for each subject across students. Row averages calculate each student's average across the subjects represented in that row.

8. Using swapaxes()

The swapaxes() function exchanges two selected axes of an array. It is useful when you need to switch specific dimensions without manually specifying the full axis order.

import numpy as np data = np.arange(1, 13).reshape(2, 2, 3) result = np.swapaxes(data, 0, 2) print("Original shape:", data.shape) print("New shape:", result.shape)

Output:

Original shape: (2, 2, 3) New shape: (3, 2, 2)

In this example, axis 0 and axis 2 exchange positions. The dimension sizes therefore change from (2, 2, 3) to (3, 2, 2).

When Is swapaxes() Useful?

  • Rearranging multidimensional datasets.
  • Changing the position of image dimensions.
  • Preparing arrays for functions that expect a different axis order.
  • Exchanging two dimensions without listing every axis.

9. Using moveaxis()

The moveaxis() function moves one or more axes from their current positions to specified destination positions. Unlike a simple axis swap, it is designed to reposition axes while retaining the relative order of the other axes.

import numpy as np data = np.zeros((2, 3, 4)) result = np.moveaxis(data, 0, -1) print("Original shape:", data.shape) print("New shape:", result.shape)

Output:

Original shape: (2, 3, 4) New shape: (3, 4, 2)

The first axis moves to the last position. The original dimensions (2, 3, 4) therefore become (3, 4, 2).

Function Purpose
transpose() Rearranges axes according to a specified order.
swapaxes() Exchanges two selected axes.
moveaxis() Moves selected axes to destination positions.

10. Working with Three-Dimensional Arrays

Axis operations become especially useful with three-dimensional data. Consider an array containing two groups, each with two rows and three columns. Its shape is (2, 2, 3).

import numpy as np data = np.arange(1, 13).reshape(2, 2, 3) print("Original shape:", data.shape) print("Sum along axis 0:") print(data.sum(axis=0)) print("Sum along axis 1:") print(data.sum(axis=1)) print("Sum along axis 2:") print(data.sum(axis=2))

Output:

Original shape: (2, 2, 3) Sum along axis 0: [[ 8 10 12] [14 16 18]] Sum along axis 1: [[ 5 7 9] [17 19 21]] Sum along axis 2: [[ 6 15] [24 33]]

Each axis operation reduces the selected dimension. The resulting array has one fewer dimension because the sum combines values along that axis.

Important: For higher-dimensional arrays, always inspect shape before and after an operation. This helps confirm which dimension has been reduced or moved.

11. Practical Activity

Activity: Student Marks and Subject Analysis

Samadhan, Pradnya, and Samiksha are analyzing a dataset containing marks for three students across four subjects. Use NumPy to inspect the dataset, transpose it, and calculate subject-wise and student-wise averages.

Tasks:

  1. Create a two-dimensional array with three students and four subjects.
  2. Display the original array and its shape.
  3. Transpose the array using .T.
  4. Print the shape of the transposed array.
  5. Calculate the average marks for each student.
  6. Calculate the average marks for each subject.
  7. Use swapaxes() on a three-dimensional array.

Sample Solution

import numpy as np marks = np.array([ [78, 85, 90, 82], [88, 76, 92, 80], [91, 87, 84, 95] ]) print("Original marks:") print(marks) print("Original shape:", marks.shape) transposed = marks.T print("Transposed marks:") print(transposed) print("Transposed shape:", transposed.shape) student_averages = marks.mean(axis=1) subject_averages = marks.mean(axis=0) print("Student averages:", student_averages) print("Subject averages:", subject_averages) three_d = np.arange(1, 13).reshape(2, 2, 3) swapped = np.swapaxes(three_d, 0, 2) print("Three-dimensional shape:", three_d.shape) print("Shape after swapaxes:", swapped.shape)

Expected key results:

  • Original shape: (3, 4)
  • Transposed shape: (4, 3)
  • Student averages: [83.75, 84.0, 89.25]
  • Subject averages: [85.6667, 82.6667, 88.6667, 85.6667], approximately.
  • Shape after swapping axes 0 and 2: (3, 2, 2)

12. Common Mistakes to Avoid

Common Mistake Correct Approach
Assuming .T converts every array into a column vector. Use reshape(-1, 1) for a one-dimensional column vector.
Confusing axis=0 and axis=1. Check the array shape and determine which dimension the operation reduces.
Using an invalid axis number. Check ndim to identify valid axis indices.
Providing an incomplete or repeated axis order to transpose(). Specify every axis exactly once.
Assuming transposition always creates an independent copy. Remember that transpose operations commonly return a view when possible.

Summary

In this lesson, we learned how to transpose NumPy arrays, rearrange dimensions, and perform operations along specific axes. We explored transpose(), the .T attribute, swapaxes(), and moveaxis() to understand how array dimensions can be exchanged or repositioned.

We also learned how axis-based operations such as sum() and mean() calculate results across rows, columns, and dimensions of multidimensional arrays. Understanding axes helps organize datasets, calculate meaningful statistics, and prepare arrays for numerical processing. Always inspect the shape of an array before and after changing its axes to confirm that the resulting structure matches the requirements of your task.