Gemini
Gemini

Reputation: 475

Modify numpy array based on previous value

I have a np array, let's say

[1, 1, 1, 1, 0, 1, 0, 1, 0]

Now I want to modify the number at index i s.t. it is 0, if one of the previous n elements was a 1. But this calculation should not be static w.r.t to the original array, but dynamic, i.e. considering already changed values. Let's say n=2, then I want to get

[1, 0, 0, 1, 0, 0, 0, 1, 0]

How do I do that efficiently without a for loop? Simple indexing will run over the whole array in one iteration, ignoring newly changed values, meaning the result would be

[1, 0, 0, 0, 0, 0, 0, 0, 0]

right?

Update: In a loop I would do this:

for i in range(a.shape[0]):
    FoundPrevious = False
    for j in range(n):
        if i - j < 0:
            continue
        if a[i - j] == 1:
            FoundPrevious = True
            break
    if FoundPrevious:
        a[i] = 0

Upvotes: 0

Views: 1663

Answers (2)

Daniel R. Livingston
Daniel R. Livingston

Reputation: 1229

As other answerers and commenters have noted, the intrinsic interative nature of the problem makes a solution without a for-loop non-obvious.

Another approach to simplifying this problem is:

import numpy as np

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

for i in range(a.shape[0]):
    i0 = i - 2 if i >= 2 else 0
    if 1 in a[i0:i]:
        a[i] = 0

print(a)
# [1 0 0 1 0 0 0 1 0]

Upvotes: 1

cs95
cs95

Reputation: 402553

The problem is inherently iterative, but you can simplify things by doing a single pass over your list.

arr = [1, 1, 1, 1, 0, 1, 0, 1, 0]
n = 2
newarr = []

for i in arr:
    newarr.append(0 if sum(newarr[-n:]) else i)

print (newarr)
[1, 0, 0, 1, 0, 0, 0, 1, 0]

Upvotes: 4

Related Questions