numpy.trim_zeros() in Python
The numpy.trim_zeros() trims the leading and/or trailing zeros from a 1-D array or sequence.
Syntax
numpy.trim_zeros(filt, trim='fb')
Parameter
The numpy.trim_zeros() function consists of two parameters, which are as follows:
filt : This parameter represents the 1-D array Input array.
trim : It is an optional parameter which takes a string with ‘f’ representing trim from front and ‘b’ to trim from the back. Default is ‘fb’, trim zeros from both front and back of the array.
Return
This function returns the result of trimming the input. The input data type is preserved.
Example 1
# Python program explaining
# numpy.trim_zeros() function
import numpy as np
# input array
inp_arr = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
print("Input Array: ")
print(inp_arr)
#triming the zeros in the input array
out_arr= np.trim_zeros(inp_arr)
print("After trimming the zeros: ")
print(out_arr)
Output
Input Array:
[0 0 0 1 2 3 0 2 1 0]
After trimming the zeros:
[1 2 3 0 2 1]