Python – Identify groups of consecutive 0’s and replace them

Im trying to identify groups of n-length consecutive 0’s (0, 00, … 00000, etc.) in an array and then replace them with the average value from values before and after the run.

So let’s say:

a = [1, 2, 0, 0, 0, 3, 3, 0, 3]

In this case, it would check the array, pick out the two runs and change them. The output should look like this:

a = [1, 2, 2.5, 2.5, 2.5, 3, 3, 3, 3]

I tried but it only applied it to the first instance. Is there any way to do this for the whole array (can be quite long)?

Answer

I think this handles it.

newa = []
span = 0
for n in a:
    # Is this number non-zero?
    if n:
        # Yes.  Have we just passed a string of zeros?
        if span:
            # Yes.  Average this value and the last non-zero value
            # and duplicate for as many zeros as we saw.
            avg = (newa[-1] + n) / 2
            newa.extend( [avg] * span )
            span = 0
        # Always add this number to the new list.
        newa.append( n )
    else:
        # No, this number was a zero.  Just count it.
        span += 1

Can this series end with a span of zeros? Only you know whether that’s a concern or not.

EDIT to ignore series longer than 5.

newa = []
span = 0
for n in a:
    # Is this number non-zero?
    if n:
        # Yes.  Have we just passed a string of zeros?
        if span:
            # Yes.  Average this value and the last non-zero value
            # and duplicate for as many zeros as we saw.
            if span > 5:
               avg = 0
            else:
               avg = (newa[-1] + n) / 2
            newa.extend( [avg] * span )
            span = 0
        # Always add this number to the new list.
        newa.append( n )
    else:
        # No, this number was a zero.  Just count it.
        span += 1

Leave a Reply

Your email address will not be published. Required fields are marked *