Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
numpy

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

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"))
Implementing the trim_zeros() function

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.

RELATED TAGS

python
communitycreator
numpy

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring