numpy.trim_zeros() in Python

numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence.

Syntax: numpy.trim_zeros(arr, trim)

Parameters:
arr : 1-D array or sequence
trim : trim is an optional parameter with default value to be ‘fb'(front and back) we can either select ‘f'(front) and ‘b’ for back.



Returns: trimmed : 1-D array or sequence (without leading and/or trailing zeros as per user’s choice)

Code 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as geek 
  
gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))
  
# without trim parameter
# returns an array without leading and trailing zeros 
  
res = geek.trim_zeros(gfg)
print(res)

chevron_right


Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10])

Code 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as geek 
gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))
  
# without trim parameter
# returns an array without any leading  zeros 
  
res = geek.trim_zeros(gfg, 'f')
print(res)

chevron_right


Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0])

Code 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as geek 
gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))
  
# without trim parameter
# returns an array without any trailing  zeros 
  
res = geek.trim_zeros(gfg, 'b')
print(res)

chevron_right


Output :array([0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10])


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.