I have a 1D numpy numpy array with integers, where I want to replace zeros with the previous non-zero value if and only if the next non-zero value is the same.
For example, an array of:
in: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1])
out: [1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1]
should become
out: [1,1,1,1,0,0,2,0,3,3,3,3,3,1,1,1]
Is there a vectorized way to do this? I found some way to fill values of zeros here, but not how to do it with exceptions, i.e. to not fill the zeros that are within integers with different value.
Here's a vectorized approach taking inspiration from
NumPy based forward-filling
for the forward-filling part in this solution alongwithmasking
andslicing
-Sample runs -