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
Try np.isin:
array[np.isin(array, some_values)] = 0
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With