Humble_beginner
Humble_beginner

Reputation: 3

Replace matching elements within two arrays with a different value using for loops and if conditions in python 3

I have two arrays:

import numpy as np

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

I would like to replace the elements of a with -3 if the same elements appear in b. I would like to do this with a for loop with/without an if condition. Here's what I have:

for i in range(len(a)):
    if a[i] == b[i]:
       a[i] == -3

        
              
print(a) 

And I get this error:

IndexError                                Traceback (most recent call last)
<ipython-input-19-5f8874f38b74> in <module>()
      7 
      8 for i in range(len(a)):
----> 9     if a[i] == b[i]:
     10        a[i] == -3
     11 

IndexError: index 4 is out of bounds for axis 0 with size 4

From my understanding it's a size discrepancy. Is there a way to solve my issue with arrays of different sizes?

Upvotes: 0

Views: 171

Answers (3)

James Tollefson
James Tollefson

Reputation: 893

You are using the indices from a to access elements from b, which is much shorter. You quickly overshoot the length of b and encounter an error. Recommend you try the following:

import numpy as np

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

for i,v in enumerate(a):
    if v in b:
        a[i] = -3
       
print(a) 

Out:

[-3  1 -3  3  4 -3  6  7 -3  9]

Explaining this behavior in depth might take a bit more space than I want to fill here but there's a pretty good tutorial here that can help you wrap your head around using listss in Python.

Upvotes: 2

Elliot Way
Elliot Way

Reputation: 243

Others have pointed out that the real issue is that you can't check membership by looping over both arrays at the same time. Using Python's in operator is a good alternative.

However, if we're in Numpy, we can use the Numpy element-wise version of the same thing:

a[np.isin(a, b)] = -3

np.isin(a,b) returns a boolean ndarray indicating whether each element of a was in b, which we can use to index a and only set the values that were in b to -3.

Upvotes: 2

python_user
python_user

Reputation: 7123

The following will work for a python list. This is not a numpy based solution

a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b=[8,2,5,0]
common=set(a).intersection(b) # {8, 0, 2, 5}
for i in range(len(a)):
    if a[i] in common:
        a[i]=-3
print(a) # [-3, 1, -3, 3, 4, -3, 6, 7, -3, 9]

Upvotes: 1

Related Questions