If I define the following function:
def f(x):
if x<1.:
return 0.
else:
return x
and I try to apply it to an array (in order to have another array as output)
import numpy as np
X=np.linspace(0.,2.,100)
print f(X)
it returns the following error:
ValueError: The truth value of an array with
more than one element is ambiguous. Use a.any() or a.all()
Of course I could solve the problem by applying the function to each component of the array separately, but it doesn't seem to be the most efficient way. What is the right way to define the function?
mapover all the elementsX<1. Could you use that 'mask' as a way of setting many values to 0 at once? To avoid loops innumpyyou have to step outside of the box a bit; instead of focusing on changing one element at a time, think about how you can select and change a whole set of elements at once.np.wheref(X). A pythonifis a simple True/False test; it does not iterate in any way.X<1produces a boolean array, many True/False values. The error says it can't use a such an array in the scalarifcontext.