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.
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])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With