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.
            Asked
            
        
        
            Active
            
        
            Viewed 1.0k times
        
    1
            
            
         
    
    
        Arnold Royce
        
- 21
- 1
- 1
- 4
- 
                    1what does your code look like? – Chris Jun 10 '21 at 20:07
- 
                    @Chris Hello. I am trying to write code that work like this tool https://sndeep.info/en/tools/checksum_calculator . And in the second section I have to change values. – Arnold Royce Jun 10 '21 at 20:20
- 
                    Have a look at [this answer](https://stackoverflow.com/a/19666680/10940584) - 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). – generic_stackoverflow_user Jun 10 '21 at 20:09
2 Answers
12
            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]
 
    
    
        Nk03
        
- 14,699
- 2
- 8
- 22
- 
                    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. – Arnold Royce Jun 10 '21 at 20:13
- 
                    1I'm hardcoding both the values here. If you want `dynamic` values **don't** `hardcode` the values and replace them with suitable formula. – Nk03 Jun 10 '21 at 20:16
- 
                    
2
            
            
        Numpy provide the comparison to a scalar with the standard == operator, such that arr == v return a boolean array. Taking arr[arr == v] takes the subset (or slice) 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])
 
    
    
        Maxime A
        
- 90
- 1
- 9
- 
                    what if I have multiple numbers to change , not two of them but every number in given array with some formula ? Thank you. – Arnold Royce Jun 10 '21 at 20:17