0

Let's say I have an array that looks like this:

a = np.array([0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0])

I want to fill the values that are between 1's with 1's. So this would be the desired output:

a = np.array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0])

I have taken a look into this answer, which yields the following:

array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1]) 

I am sure this answer is really close to the output I want. However, although tried countless times, I can't change this code into making it work the way I want, as I am not that proficient with numpy arrays. Any help is much appreciated!

Community
  • 1
  • 1
La Cordillera
  • 410
  • 5
  • 17

2 Answers2

6

Try this

b = ((a == 1).cumsum() % 2) | a

Out[10]:
array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0], dtype=int32)

From @Paul Panzer: use ufunc.accumulate with bitwise_xor

b = np.bitwise_xor.accumulate(a)|a
Andy L.
  • 24,909
  • 4
  • 17
  • 29
1

Try this:

import numpy as np

num_lst = np.array(
[0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0])

i = 0
while i < len(num_lst): # Iterate through the list
    if num_lst[i]: # Check if element is 1 at i-th position
        if not num_lst[i+1]: # Check if next element is 0
            num_lst[i+1] = 1 # Change next element to 1
            i += 1 # Continue through loop
        else: # Check if next element is 1
            i += 2 # Skip next element
    else:
        i += 1 # Continue through loop


print(num_lst)

This is probably not the most elegant way to execute this, but it should work. Basically, we loop through the list to find any 1s. When we find an element that is 1, we check if the next element is 0. If it is, then we change the next element to 1. If the next element is 1, that means we should stop changing 0s to 1s, so we jump over that element and proceed with the iteration.

Jake Tae
  • 1,681
  • 1
  • 8
  • 11