Removing leading zeros of a numpy array without using a for loop

  • 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] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: