F L F L - 5 months ago 18
Python Question

Replace value in array with condition

I have this simplified program to replace values in array which fulfill the conditions:

formula1=2*2
formula2=5*2
formula3=4*4

array = np.random.rand(2,4,10)
for n,i in enumerate(array):
if i>0.5: #find value in array with this condition
formula = formula1
array[n] = array[n]*formula #replace the found value with this value
elif i <0.1:
formula = formula2
array[n] = array[n]*formula
else:
formula = formula3
array[n] = array[n]*formula
print array


It resulted in error message:'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'. Any suggestion?

Answer

Try:

for n,i in np.ndenumerate(array):
    ...