3

I know how to replace all elements of numpy array that are greater than some values, like array[array > 0] = 0, but I don't really know how to replace all elements that are equal to some values without using for loop, like below can achieve what I want but is there any way not to use the for loop?

Sorry for being unclear, some_values here is a list, like [7, 8, 9]

for v in some_values:
    array[array == v] = 0

2 Answers 2

5

Try np.isin:

array[np.isin(array, some_values)] = 0
Sign up to request clarification or add additional context in comments.

Comments

2

Just use:

a[a==replacee] = replacer

For 1:1 replacements without any for loop. Numpy is meant to be vectorized & each operation is performed this way so you don't need for loops.

In case you want to replace a whole list of values with a single one, you might use isin() as follows:

a[a.isin(replacee_list)] = replacer

In case you want to use a set of values with another set of values from a different array, use:

a = np.copyto(a, replacer_array, where = a.isin(replacee_list))

5 Comments

I don't think this answers the question. This is identical to the inside of the for loop.
Yeah its identical to whats inside the loop but eliminating the loop is the answer.
How is it eliminating the for loop? Did you try your code when some_values is a iterable, e.g. a list?
Sorry for being unclear, I updated the question, some_values here is a list, like [7, 8, 9]
Ohh With the updated question, I see the problem now. If there is a whole list to compare of course single comparison wont work and isin() is the way to go!

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.