What is the numpy.trim_zeros() function in Python?

Overview

The trim_zeros() function in Python is used to trim out the leading zeros from an input 1-D array.

Syntax

The trim_zeros() function takes the syntax below:

numpy.trim_zeros(filt, trim='fb')
Syntax for the trim_zeros() function in Python

Parameter values

The trim_zeros() function takes the following parameter values:

  • filt: This is the input array. It is a required parameter.
  • trim: This is a string with an 'f', which represents trim from the front, and 'b' , which represents trim from the back. This is an optional parameter.

Return value

The trim_zeros() function returns an array whose leading zero entry(ies) is trimmed.

Example

import numpy as np
# creating an input array
a = np.array([0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0])
print(a)
# trimming the zero entries from fromt
print(np.trim_zeros(a))
# trimming the zero entries from fromt
print(np.trim_zeros(a, "b"))

Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array, a , using the array() function.
  • Line 4: We print the input array, a.
  • Line 7: We trim the zeros entries from the front of the array using the trim_zeros() function. We print the result to the console.
  • Line 10: We trim the zeros entries from the back of the array using the trim_zeros() function. We print the result to the console.

Free Resources