Search code examples
pythonnumpynumpy-ndarray

How to replace values in numpy array at the same time


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.


Solution

  • 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]