mouride touba mouride touba - 1 month ago 12
Python Question

Slice an array starting from first nonzero element

I have an array with leading zeros, and I want the array from the first nonzero element.
For example, I have an array

x=[0,0,0,0,0,3,2,0,0,4,5]


I want to obtain :

x=[3,2,0,0,4,5]

Answer

Use np.argmax on non-zeros to get the starting non-zero index and then simply slice it -

x[(x!=0).argmax():]

Sample run -

In [71]: x
Out[71]: array([0, 0, 0, 0, 0, 3, 2, 0, 0, 4, 5])

In [72]: x[(x!=0).argmax():]
Out[72]: array([3, 2, 0, 0, 4, 5])
Comments