- A+

Category：Languages

How can I remove only the leading zeroes from a numpy array without using for a loop?

`import numpy as np x = np.array([0,0,1,1,1,1,0,1,0,0]) # Desired output array([1, 1, 1, 1, 0, 1, 0, 0]) `

I have written the following code

`x[min(min(np.where(x>=1))):] `

I was wondering if there is a more efficient solution.

You can use `np.trim_zeros(x, 'f')`

.

The 'f' means to trim the zeros from the front. Option 'b' would trim the zeros from the back. Default option 'fb' trims them from both sides.

`x = np.array([0,0,1,1,1,1,0,1,0,0]) # [0 0 1 1 1 1 0 1 0 0] np.trim_zeros(x, 'f') # [1 1 1 1 0 1 0 0] `