Home > Software engineering >  Iterating over numpy elements with interruptions
Iterating over numpy elements with interruptions

Time:01-24

I am currently facing the following problem:
I have two arrays:

a=np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
b=np.array([False, False, False, True, False, False, False, False, False, False, False])

I start iterating over array a from an arbitrary starting point, adding the elements from the beginning of the array. So doing this for the first two steps (as indicated by the indices), starting from index 2:

step_1=np.array([1, 2, 4, 4, 5, 6, 7, 8, 9, 10, 11])
step_2=np.array([1, 2, 4, 6, 5, 6, 7, 8, 9, 10, 11])

[Important: I don't create a new array every time. this is just to visualize the steps]

At the same time I start iterating over array b. Whenever bshows True, I skip the step of adding the numbers and simply continue with the next iteration step, but without advancing the position of the number that I want to add.

import numpy as np
offset=2
position=0
for index in range(offset,len(a)):
    if b[index]:
        continue
    a[index]=a[index] a[position]
    position  =1
>>>a=array([ 1,  2,  4,  4,  7, 10, 11, 15, 19, 21, 26])

You can see in the result that the fourth element stayed 4 and the 2 that would normally have been added went to the 5 (resulting in the 7).

Is there any way to simplify my code? I have to run it very often and wonder if there is a way that could make my live easier instead of having to go through the if-statement every time while also adding 1 to the position variable.

CodePudding user response:

You can do

indices = np.flatnonzero(np.logical_not(b))[offset:]
for s,t in enumerate(indices):
    a[t]  = a[s position]
  •  Tags:  
  • Related