1

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()

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You can make a boolean mask and use it like this:

mask = np.logical_or(main == repl[0], main == repl[1])
main[mask] = -1

Comments

0

Not sure if there's any native numpy method for this, but in old fashion python you can do:

import numpy as np

main = np.random.randint(5, size=(3, 4))
repl = [2,3]
for k1, v1 in enumerate(main):
    for k2, v2 in enumerate(v1):
        if(v2 in repl):
            main[k1][k2] = -1
print(main)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.