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.