Home > database >  numpy array replace value with a conditional loop
numpy array replace value with a conditional loop

Time:09-19

I have a numpy array,

myarray= np.array([49, 7, 44, 27, 13, 35, 171])

i wanted to replace the values if it is greater than 45, so i applied the below code

myarray=np.where(myarray> 45,myarray - 45, myarray)

but this is applied only once in that array, for example, the above array becomes

myarray= np.array([4, 7, 44, 27, 13, 35, 126])

Expected array

myarray= np.array([4, 7, 44, 27, 13, 35, 36])

How do i run the np.where till the condition is satisfied? basically in the above array i dont want any value to be greater than 45, is there a pythonic way of doing it. Thanks in advance.

CodePudding user response:

Well the subtraction happens only once, since you did the operation only once, hence 171 - 45 => 126 and the operation has completed. Try using the modulo operator if you wanna do it this way.

myarray = np.array([49, 7, 44, 27, 13, 35, 171])

myarray = np.where(myarray> 45, myarray % 45, myarray)

print(myarray)

The output matches your prompt.

[ 4  7 44 27 13 35 36]

CodePudding user response:

Not the most pythonic or even optimal way, but pretty easy to understand. You can try this:

import numpy as np
myarray= np.array([49, 7, 44, 27, 13, 35, 171])

for i in range(len(myarray)):

while(myarray[i]>45):
    myarray[i]=myarray[i]-45

print(myarray)

  • Related