Abdelrahman Elkady Abdelrahman Elkady - 5 days ago 6
Python Question

Replace elements in 2D array based on occurrence in another array

I need to replace elements in Numpy 2D arrays based on a condition that the element appears in some other

replacement
array

For example:

>>> main = np.random.randint(5, size=(3, 4))
>>> main
array([[1, 2, 4, 2],
[3, 2, 3, 2],
[4, 4, 2, 3]])
>>> repl = [2,3]
>>> main[main in repl] = -1


I would like to have all values in
repl
changed to -1, so I expect main to be:

[[1, -1, 4, -1],
[-1, -1, -1, -1],
[4, 4, -1, -1]]


However a
ValueError
is raised while trying to have
in
inside the condition of replacement


ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Answer

We can use np.in1d to create a flattened mask of all such occurrences and set those as -1 in the flattened input, like so -

main.ravel()[np.in1d(main, repl)] = -1

Alternatively, we can use np.putmask and thus avoid np.ravel() to avoid the explicit flattening, like so -

np.putmask(main, np.in1d(main, repl), -1)
Comments