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?

3sm1r
  • 520
  • 4
  • 19
  • 1
    You could try to use `map` over all the elements – Abass Sesay Jul 17 '19 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 – Devesh Kumar Singh Jul 17 '19 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. – hpaulj Jul 17 '19 at 17:42
  • 1
    Just in case it wasn't clear from the duplicates, use `np.where` – DeepSpace Jul 17 '19 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. – hpaulj Jul 17 '19 at 18:04

1 Answers1

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.
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40