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?
i=4what shouldb[i]return? Assuming,secondArrayisb, that is. PythonTutor is a great tool for these kind of questions.inoperator allows to check if an element is in a list.a[np.in1d(a,b)] = -3Just use lists if you aren't actually going to use numpy