![]() |
VOOZH | about |
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:
[3 4 0 5]
Explanation: np.trim_zeros(a) removes both leading and trailing zeros by default (trim='fb'). Zeros in the middle remain unchanged.
numpy.trim_zeros(filt, trim='fb')
Parameter:
Returns: A new 1-D NumPy array with the specified zeros removed.
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.
[1 2 3 0]
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.
[0 1 2]
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.
[]
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.