numpy.trim_zeros() in Python (original) (raw)
Last Updated : 21 Jun, 2025
**numpy.trim_zeros() removes the leading and trailing zeros from a 1-D array. It is often used to clean up data by trimming unnecessary zeros from the beginning or end of the array. **Example:
Python `
import numpy as np
a = np.array([0, 0, 3, 4, 0, 5, 0, 0]) res = np.trim_zeros(a) print(res)
`
**Explanation: np.trim_zeros(a) removes both leading and trailing zeros by default (trim='fb'). Zeros in the middle remain unchanged.
**Syntax
numpy.trim_zeros(filt, trim='fb')
**Parameter:
- **filt (array_like): A 1-D array of numeric values from which zeros will be trimmed.
- **trim (str, optional): Indicates which zeros to remove, 'f' for leading (front), 'b' for trailing (back) and 'fb' (default) for both.
**Returns: A new 1-D NumPy array with the specified zeros removed.
Examples
**Example 1: In this example, we use the parameter trim='f' to remove the leading zeros from the beginning of the array, while keeping the zeros at the end unchanged.
Python `
import numpy as np a = np.array([0, 0, 1, 2, 3, 0]) res = np.trim_zeros(a, trim='f') print(res)
`
**Explanation: np.trim_zeros(a, trim='f') removes only the leading zeros from the beginning of the array. Trailing zeros are preserved, resulting in [1, 2, 3, 0].
**Example 2: In this example, we use the parameter trim='b' to remove the trailing zeros from the end of the array, while keeping the leading zeros at the beginning unchanged.
Python `
import numpy as np a = np.array([0, 1, 2, 0, 0]) res = np.trim_zeros(a, trim='b') print(res)
`
**Explanation: np.trim_zeros(a, trim='b') removes only the trailing zeros from the end of the array. Leading zeros are kept intact, resulting in [0, 1, 2].
**Example 3: In this example, all elements are zeros. Since **np.trim_zeros() removes zeros from both ends by default, the result is an empty array.
Python `
import numpy as np a = np.array([0, 0, 0, 0]) res = np.trim_zeros(a) print(res)
`
**Explanation: np.trim_zeros(a) removes zeros from both ends by default (trim='fb'). Since the array contains only zeros, the result is an empty array.