Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all elements of Python NumPy Array that are EQUAL to some values

Tags:

python

numpy

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
like image 223
Qimin Chen Avatar asked Nov 30 '25 08:11

Qimin Chen


2 Answers

Try np.isin:

array[np.isin(array, some_values)] = 0
like image 97
mathfux Avatar answered Dec 01 '25 21:12

mathfux


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))
like image 21
Hamza Avatar answered Dec 01 '25 20:12

Hamza