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

Expand and Squeeze Dimensions

Learn how to add new dimensions to NumPy arrays and remove unnecessary dimensions of size one. Explore expand_dims(), squeeze(), reshape(), and indexing techniques with detailed examples, shape analysis, and practical data-processing activities.

1. Learning Objectives

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

  • Understand dimensions and array shapes in NumPy.
  • Add a new dimension using np.expand_dims().
  • Use np.newaxis to create row and column arrays.
  • Remove dimensions of size one using np.squeeze().
  • Use the axis argument to control dimension expansion and removal.
  • Understand the difference between reshaping and expanding dimensions.
  • Inspect array shapes before and after dimension operations.
  • Apply these operations to practical numerical datasets.

2. Understanding Array Dimensions

A NumPy array can have one or more dimensions. A one-dimensional array stores elements in a sequence, while a two-dimensional array organizes elements into rows and columns. Higher-dimensional arrays can represent batches, images, and other structured datasets.

The ndim attribute returns the number of dimensions, and the shape attribute reports the size of the array along each dimension.

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

Output:

Array: [10 20 30 40] Dimensions: 1 Shape: (4,)

The shape (4,) means that the array has one dimension containing four elements. It is not the same as a two-dimensional array with shape (1, 4) or (4, 1).

1D Array Row Array Column Array 10 20 30 40 10 20 30 40 10 20 30 40 Shape: (4,) Shape: (1, 4) Shape: (4, 1)

The same four values can have different array shapes depending on the number and size of dimensions.

3. What Is Expanding a Dimension?

Expanding dimensions means inserting a new axis into an existing array. This changes the array's shape and increases its number of dimensions by one, but it does not add new data values.

For example, a one-dimensional array with shape (4,) can be converted into a row-shaped two-dimensional array with shape (1, 4), or a column-shaped array with shape (4, 1).

import numpy as np values = np.array([10, 20, 30, 40]) row_array = np.expand_dims(values, axis=0) column_array = np.expand_dims(values, axis=1) print("Original shape:", values.shape) print("Row shape:", row_array.shape) print("Column shape:", column_array.shape)

Output:

Original shape: (4,) Row shape: (1, 4) Column shape: (4, 1)
Remember: Expanding a dimension changes the structure of an array, not the number of stored elements. All three arrays above contain four values.

4. Using np.expand_dims()

The np.expand_dims() function inserts a new dimension at the specified axis. The original dimensions retain their relative order, and the new dimension has a size of one.

import numpy as np values = np.array([1, 2, 3, 4]) expanded = np.expand_dims(values, axis=0) print(expanded) print("Dimensions:", expanded.ndim) print("Shape:", expanded.shape)

Output:

[[1 2 3 4]] Dimensions: 2 Shape: (1, 4)

Expanding at Axis 0

For a one-dimensional array, axis=0 inserts a new leading dimension. The result has one row and the original number of columns.

import numpy as np values = np.array([5, 10, 15]) result = np.expand_dims(values, axis=0) print(result) print(result.shape)

Output:

[[ 5 10 15]] (1, 3)

Expanding at Axis 1

For a one-dimensional array, axis=1 inserts a dimension after the original axis. The result has one column for each row.

import numpy as np values = np.array([5, 10, 15]) result = np.expand_dims(values, axis=1) print(result) print(result.shape)

Output:

[[ 5] [10] [15]] (3, 1)
Important: The axis value must be valid for the resulting number of dimensions. If the specified axis is out of range, NumPy raises an error.

5. Using np.newaxis

NumPy's np.newaxis is another convenient way to insert a dimension through array indexing. It is commonly used to convert one-dimensional arrays into row or column arrays.

import numpy as np values = np.array([10, 20, 30, 40]) row_array = values[np.newaxis, :] column_array = values[:, np.newaxis] print("Row array:") print(row_array) print("Column array:") print(column_array)

Output:

Row array: [[10 20 30 40]] Column array: [[10] [20] [30] [40]]
Expression Result Shape Explanation
values[np.newaxis, :] (1, 4) Adds a new axis before the existing axis.
values[:, np.newaxis] (4, 1) Adds a new axis after the existing axis.
Tip: Use np.expand_dims() when you want to state the axis explicitly. Use np.newaxis when indexing syntax makes the intended shape easy to understand.

6. Expanding Dimensions in Two-Dimensional Arrays

Dimension expansion is not limited to one-dimensional arrays. You can insert a new axis into a two-dimensional array to create a three-dimensional array. This is useful when a processing function expects an additional batch or channel dimension.

import numpy as np matrix = np.array([ [1, 2, 3], [4, 5, 6] ]) expanded_start = np.expand_dims(matrix, axis=0) expanded_end = np.expand_dims(matrix, axis=2) print("Original shape:", matrix.shape) print("Expanded at axis 0:", expanded_start.shape) print("Expanded at axis 2:", expanded_end.shape)

Output:

Original shape: (2, 3) Expanded at axis 0: (1, 2, 3) Expanded at axis 2: (2, 3, 1)

In the first result, a new leading dimension is inserted. In the second result, a new dimension is added at the end. The original rows and columns remain in their original order.

7. What Is Squeezing an Array?

Squeezing removes dimensions whose size is exactly one. NumPy's np.squeeze() function can reduce the number of dimensions without removing the actual data values.

For example, an array with shape (1, 4) can be squeezed to shape (4,). Similarly, an array with shape (2, 3, 1) can be squeezed to shape (2, 3).

import numpy as np row_array = np.array([[10, 20, 30, 40]]) result = np.squeeze(row_array) print("Original shape:", row_array.shape) print("Squeezed shape:", result.shape) print(result)

Output:

Original shape: (1, 4) Squeezed shape: (4,) [10 20 30 40]
Before Squeeze After Squeeze 10 20 30 40 10 20 30 40 Shape: (1, 4) Shape: (4,) Only the dimension of size one is removed

Squeezing changes the shape by removing eligible dimensions, while preserving the data values.

8. Using np.squeeze()

By default, np.squeeze() removes all dimensions with size one. Dimensions larger than one remain unchanged.

import numpy as np data = np.zeros((1, 3, 1, 4, 1)) result = np.squeeze(data) print("Original shape:", data.shape) print("Squeezed shape:", result.shape)

Output:

Original shape: (1, 3, 1, 4, 1) Squeezed shape: (3, 4)

The original array has five dimensions. Three dimensions have size one, so they are removed. The dimensions of sizes three and four remain.

Removing a Specific Axis

You can use the axis argument to remove a particular dimension. That dimension must have size one.

import numpy as np data = np.zeros((2, 1, 3)) result = np.squeeze(data, axis=1) print("Original shape:", data.shape) print("Result shape:", result.shape)

Output:

Original shape: (2, 1, 3) Result shape: (2, 3)
Important: Attempting to squeeze an axis whose size is greater than one raises a ValueError. For example, axis 0 cannot be squeezed from an array with shape (2, 1, 3).

9. Expand Dimensions vs Squeeze Dimensions

These operations perform opposite structural changes. Expanding inserts a dimension of size one, while squeezing removes dimensions of size one. Neither operation is intended to add or remove actual data elements.

Feature expand_dims() squeeze()
Purpose Adds a new axis. Removes axes of size one.
Dimension count Increases by one. Decreases by the number of removed axes.
Example input shape (4,) (1, 4, 1)
Example output shape (1, 4) (4,)
Element count Remains unchanged. Remains unchanged.
import numpy as np values = np.array([10, 20, 30, 40]) expanded = np.expand_dims(values, axis=0) squeezed = np.squeeze(expanded) print("Original:", values.shape) print("Expanded:", expanded.shape) print("Squeezed:", squeezed.shape)

Output:

Original: (4,) Expanded: (1, 4) Squeezed: (4,)

10. Reshape vs Expand Dimensions

Both reshape() and expand_dims() can change the shape of an array, but their purposes are different. Reshape allows you to specify a complete new shape, while expand_dims inserts a new dimension at a chosen position.

import numpy as np values = np.array([1, 2, 3, 4]) using_reshape = values.reshape(1, 4) using_expand_dims = np.expand_dims(values, axis=0) print(using_reshape.shape) print(using_expand_dims.shape)

Output:

(1, 4) (1, 4)
Function Best Used When
reshape() You want to specify the complete desired array shape.
expand_dims() You want to insert a dimension at a specific axis.
squeeze() You want to remove dimensions whose size is one.
np.newaxis You want to add a dimension using indexing syntax.

11. Practical Example: Preparing Data for Processing

In numerical applications, the shape expected by a function may differ from the shape of the available data. A function may expect a two-dimensional column array, while the original values are stored in a one-dimensional array.

Expanding the dimensions can help match the expected structure. After processing, squeezing can remove an unnecessary dimension if the resulting shape allows it.

import numpy as np temperatures = np.array([24.5, 25.0, 26.2, 23.8]) column_data = np.expand_dims(temperatures, axis=1) print("Original shape:", temperatures.shape) print("Column shape:", column_data.shape) normalized = column_data - column_data.mean(axis=0) print("Normalized shape:", normalized.shape) result = np.squeeze(normalized) print("Final shape:", result.shape) print(result)

Expected key results:

Original shape: (4,) Column shape: (4, 1) Normalized shape: (4, 1) Final shape: (4,)

The values are arranged into a column for processing. The mean is calculated along the column dimension, and squeezing then returns the result to a one-dimensional shape.

Best practice: Always check the shape required by the next operation. A correctly shaped array helps prevent broadcasting mistakes and dimension mismatch errors.

12. Practical Activity

Activity: Prepare Student Marks for Analysis

Samadhan, Pradnya, and Samiksha are preparing student marks for a numerical analysis workflow. The marks are initially stored in a one-dimensional array, but the next processing step requires a column-shaped array.

Tasks:

  1. Create a one-dimensional array containing four marks.
  2. Display its shape and number of dimensions.
  3. Convert it into a column array using expand_dims().
  4. Create a row array using np.newaxis.
  5. Add another size-one dimension to the column array.
  6. Use squeeze() to remove size-one dimensions.
  7. Verify the shapes at every stage.

Sample Solution

import numpy as np marks = np.array([78, 85, 90, 82]) print("Original shape:", marks.shape) print("Original dimensions:", marks.ndim) column_marks = np.expand_dims(marks, axis=1) print("Column shape:", column_marks.shape) print(column_marks) row_marks = marks[np.newaxis, :] print("Row shape:", row_marks.shape) print(row_marks) extra_dimension = np.expand_dims(column_marks, axis=0) print("Extra dimension shape:", extra_dimension.shape) final_marks = np.squeeze(extra_dimension) print("Squeezed shape:", final_marks.shape) print(final_marks)

Expected key results:

  • Original shape: (4,)
  • Column shape: (4, 1)
  • Row shape: (1, 4)
  • Extra dimension shape: (1, 4, 1)
  • Squeezed shape: (4,)
  • The original four marks are preserved.

13. Common Mistakes to Avoid

Common Mistake Correct Approach
Assuming expanding a dimension adds more data values. Remember that expansion changes shape, not element count.
Assuming squeeze() removes every dimension. Only dimensions with size one are removed.
Trying to squeeze an axis whose size is greater than one. Check the shape before specifying the squeeze axis.
Confusing shape (4,) with (1, 4). Use shape and ndim to inspect array structure.
Using the wrong axis in expand_dims(). Determine where the new size-one dimension should appear.

Summary

In this lesson, we learned how to expand and squeeze NumPy array dimensions. We used expand_dims() and np.newaxis to insert new axes, converting one-dimensional arrays into row arrays, column arrays, and higher-dimensional structures. We also explored squeeze() to remove dimensions whose size is one.

We compared these techniques with reshape() and learned how shape and ndim help verify array structure. Expanding and squeezing dimensions are useful when preparing data for numerical calculations, broadcasting, and functions that require specific input shapes. Always inspect the array shape before and after these operations to ensure that the structure matches the requirements of the next processing step.