I have numpy array with random numbers. For example like this
[7 1 2 0 2 3 4 0 5]
and I want to replace every number at the same time if number from this array = 7, I want to replace it with 2 , also if number = 2, replace it with 3. So it will be like [2 1 3 0 3 3 4 0 5] . I have tried it with np.where but can't change any of them.
2 Answers
It's better to use np.select if you've multiple conditions:
a = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5])
a = np.select([a == 7, a == 2], [2, 3], a)
OUTPUT:
[2 1 3 0 3 3 4 0 5]
3 Comments
Arnold Royce
Thank you @Nk03 for your answer. What if when this array is generated randomly and I have formula for number change? I mean I want to do multiple changes but not always know which number will be first my be
7 will be second , so it will be replaced with 3 that I do not want that. I hope you understand what I mean.Nk03
I'm hardcoding both the values here. If you want
dynamic values don't hardcode the values and replace them with suitable formula.arilwan
short and precise.
Numpy provide the comparison to a scalar with the standard == operator, such that arr == v return a boolean array, often called a mask. The masked selection arr[arr == v] takes the subset of arr where the condition is met, so this snippet should work.
import numpy as np
arr = np.array([7, 1, 2, 0, 2, 3, 4, 0, 5])
arr[arr == 7] = 2
arr
array([2, 1, 2, 0, 2, 3, 4, 0, 5])
2 Comments
Arnold Royce
what if I have multiple numbers to change , not two of them but every number in given array with some formula ? Thank you.
Maxime A
In this case it's possible to either join the masks, using and
| : arr[(arr == 7) | (arr == 5)] = 2, or do it sequentially with statements similar to the ones in the answer.
myarray[myarray == 2] = 3thenmyarray[myarray == 7] = 2so that the values changed by the second condition aren't altered by the first replacement (unless that is the intent).