Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim / strip zeros of a numpy array

How to remove leading / trailing zeros of a numpy array?

import numpy as np
a = np.array([0,0,0,3,2,-1,0,0,7,9,13,0,0,0,0,0,0,0])

#Desired output
[3,2,-1,0,0,7,9,13]

This doesn't work:

a[a != 0]    

because it would remove all zeros including the zeros which are inside.

like image 737
Basj Avatar asked Jan 04 '16 14:01

Basj


1 Answers

Use numpy.trim_zeros:

>>> import numpy as np
>>> a = np.array([0,0,0,3,2,-1,0,0,7,9,13,0,0,0,0,0,0,0])
>>> np.trim_zeros(a)
array([ 3,  2, -1,  0,  0,  7,  9, 13])
like image 106
eskaev Avatar answered Sep 21 '22 07:09

eskaev