Home > Software engineering >  filling the zero elements in an array with the closest previous nonzero element
filling the zero elements in an array with the closest previous nonzero element

Time:02-02

enter image description here

I am working with a data array A which has the following behaviour when plotted. As one can see, there are some "isles" in the middle. In those areas, the A array is zero. It is assured that the remaining values are nonzero, even if on the order of 1e-9.

What I would like to do is to make the function "continuous", meaning I would like to substitute the zero values with the nonzero value that the array had before becoming zero.

Is there a fast general way this could be implemented? This is the first example I got, but future results may involve even more "isles".

I tried using np.where, but it does not seem to support a command such as "if zero, substitute with previous nonzero value in array". Or at least, I don't know how to do that.

If so, how could I write in in code?

CodePudding user response:

Given a data array a you could do this:

while np.any(a==0):
    indices=np.where(a==0)
    newvalueindices=np.subtract(indices,np.ones_like(indices))
    a[indices]=a[newvalueindices]

If you would like to avoid loops, here is another,faster solution:

zeroindices=np.where(a==0)
nonzeroindices=np.where(a!=0)
missingfrom=np.searchsorted(nonzeroindices[0],zeroindices[0])
previndices=np.subtract(missingfrom,np.ones_like(missingfrom))
a[zeroindices]=a[nonzeroindices][previndices]
  • Related