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.newaxisto 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.
Output:
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).
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).
Output:
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.
Output:
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.
Output:
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.
Output:
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.
Output:
| 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. |
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.
Output:
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).
Output:
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.
Output:
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.
Output:
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. |
Output:
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.
Output:
| 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.
Expected key results:
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.
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:
- Create a one-dimensional array containing four marks.
- Display its shape and number of dimensions.
- Convert it into a column array using
expand_dims(). - Create a row array using
np.newaxis. - Add another size-one dimension to the column array.
- Use
squeeze()to remove size-one dimensions. - Verify the shapes at every stage.
Sample Solution
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.