2

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?

5
  • 1
    You could try to use map over all the elements Commented Jul 17, 2019 at 17:36
  • Why is applying the function to each component of the array separately not the most efficient way? You need to access each element in order to apply the function on them Commented Jul 17, 2019 at 17:42
  • Look at X<1. Could you use that 'mask' as a way of setting many values to 0 at once? To avoid loops in numpy you 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. Commented Jul 17, 2019 at 17:42
  • 1
    Just in case it wasn't clear from the duplicates, use np.where Commented Jul 17, 2019 at 17:44
  • There are 2 problems with f(X). A python if is a simple True/False test; it does not iterate in any way. X<1 produces a boolean array, many True/False values. The error says it can't use a such an array in the scalar if context. Commented Jul 17, 2019 at 18:04

1 Answer 1

3

Use a map to apply that function on each item of the list

print(list(map(f, X)))

You can also define the function as a lambda function inside the map itself

print(list(map(lambda x: 0. if x<1. else x, X)))

Or just use numpy masking to select the indexes where x<1. and set them to 0.

X[X<1.] = 0.
Sign up to request clarification or add additional context in comments.

3 Comments

That is applying the function to each component of the array!
And you just killed vectorization
That's more like it! Now I don't have to search for a better duplicate link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.