We use np.expand_dims() to add a new dimension to data, and np.squeeze() to remove dimensions of size one. This helps shape data correctly for analysis or machine learning.
np.expand_dims() and np.squeeze() in NumPy
np.expand_dims(array, axis)
np.squeeze(array, axis=None)axis in expand_dims is where the new dimension is added.
axis in squeeze specifies which single-sized dimension to remove; if None, all single-sized dimensions are removed.
import numpy as np arr = np.array([1, 2, 3]) new_arr = np.expand_dims(arr, axis=0) print(new_arr.shape)
arr = np.array([[[1], [2], [3]]]) squeezed = np.squeeze(arr) print(squeezed.shape)
arr = np.array([1, 2, 3]) new_arr = np.expand_dims(arr, axis=1) print(new_arr.shape)
arr = np.array([[[1], [2], [3]]]) squeezed = np.squeeze(arr, axis=0) print(squeezed.shape)
This program shows how to add new dimensions to a 1D array and how to remove single-sized dimensions from a 3D array using np.expand_dims() and np.squeeze().
import numpy as np # Original 1D array arr = np.array([10, 20, 30]) print(f"Original shape: {arr.shape}") # Add new dimension at axis 0 expanded = np.expand_dims(arr, axis=0) print(f"Shape after expand_dims at axis 0: {expanded.shape}") # Add new dimension at axis 1 expanded2 = np.expand_dims(arr, axis=1) print(f"Shape after expand_dims at axis 1: {expanded2.shape}") # Create array with extra single dimensions arr2 = np.array([[[10], [20], [30]]]) print(f"Shape before squeeze: {arr2.shape}") # Remove all single dimensions squeezed = np.squeeze(arr2) print(f"Shape after squeeze (all single dims removed): {squeezed.shape}") # Remove single dimension only at axis 0 squeezed_axis0 = np.squeeze(arr2, axis=0) print(f"Shape after squeeze at axis 0: {squeezed_axis0.shape}")
Adding or removing dimensions does not change the data, only its shape.
Be careful with axis in squeeze: if the dimension is not size one, it will raise an error.
These functions are useful when working with libraries that expect specific input shapes.
np.expand_dims() adds a new dimension to an array at the specified axis.
np.squeeze() removes dimensions of size one from an array.
Use these to reshape data for analysis or machine learning without changing the data itself.
Practice
np.expand_dims() do to a NumPy array?Solution
Step 1: Understand the function purpose
np.expand_dims()is used to add a new axis to an array, increasing its dimensions.Step 2: Compare with other options
Removing dimensions or flattening is done by other functions likenp.squeeze()orreshape(). Changing data type is unrelated.Final Answer:
Adds a new dimension at the specified axis -> Option AQuick Check:
np.expand_dims() = Adds dimension [OK]
- Confusing expand_dims with squeeze
- Thinking it changes data values
- Assuming it flattens the array
np.expand_dims() on array a?Solution
Step 1: Check the function signature
np.expand_dims(array, axis)requires the axis parameter to specify where to add the new dimension.Step 2: Identify correct axis value
Axis=1 adds the new dimension at position 1.np.expand_dims(a, 0)(positional) andnp.expand_dims(a, axis=0)add the dimension at position 0.np.expand_dims(a, axis=2)causes an AxisError since valid axes are -2 to 1 for a 1D array.Final Answer:
np.expand_dims(a, axis=1) -> Option CQuick Check:
Use axis=1 to add dimension at position 1 [OK]
- Omitting axis keyword and confusing position
- Using wrong axis number
- Mixing axis=0 and axis=1
np.squeeze() to arr = np.array([[[1], [2], [3]]])?Solution
Step 1: Check original shape
arrhas shape (1, 3, 1) because it is a 3D array with one element in first and last dimension.Step 2: Apply np.squeeze()
np.squeeze()removes all dimensions of size 1, so the first and last dimensions are removed, leaving shape (3,).Final Answer:
(3,) -> Option AQuick Check:
squeeze removes size 1 dims = (3,) [OK]
- Assuming squeeze removes only one dimension
- Confusing original shape with squeezed shape
- Thinking squeeze flattens the array
arr = np.array([1, 2, 3]), which code will cause an error?Solution
Step 1: Check original array shape
arrhas shape (3,), so it has 1 dimension.Step 2: Validate axis values for expand_dims
Valid axis values for adding a new dimension are between -2 and 1 (inclusive) because adding a dimension increases rank by 1. Axis=3 is out of bounds and causes an error.Final Answer:
np.expand_dims(arr, axis=3) causes error -> Option DQuick Check:
Axis out of range causes error [OK]
- Using axis larger than array ndim + 1
- Confusing axis indexing with array shape
- Assuming squeeze can cause error on 1D arrays
data with shape (5, 1). You want to prepare it for a machine learning model that expects input shape (5,). Which code correctly reshapes data using np.squeeze() and np.expand_dims()?Solution
Step 1: Understand the original shape and target shape
datashape is (5, 1). The model expects (5,), so we need to remove the extra dimension.Step 2: Use np.squeeze() to remove size 1 dimension
np.squeeze(data)removes the dimension of size 1, resulting in shape (5,). Adding dimensions again is unnecessary and would change shape incorrectly.Final Answer:
np.squeeze(data) -> Option BQuick Check:
Squeeze removes extra dims to match model input [OK]
- Adding dimensions instead of removing
- Using expand_dims unnecessarily
- Not matching model expected input shape
Ready to prove it?
Pass the test and this pattern moves unknown
