5

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.

3
  • 1
    what does your code look like? Commented Jun 10, 2021 at 20:07
  • Have a look at this answer - you would probably have to run two replace operations, so maybe something like myarray[myarray == 2] = 3 then myarray[myarray == 7] = 2 so that the values changed by the second condition aren't altered by the first replacement (unless that is the intent). Commented Jun 10, 2021 at 20:09
  • @Chris Hello. I am trying to write code that work like this tool sndeep.info/en/tools/checksum_calculator . And in the second section I have to change values. Commented Jun 10, 2021 at 20:20

2 Answers 2

16

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I'm hardcoding both the values here. If you want dynamic values don't hardcode the values and replace them with suitable formula.
short and precise.
4

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

what if I have multiple numbers to change , not two of them but every number in given array with some formula ? Thank you.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.