0

My code is:-

import numpy as np
def f(x):
    if x<=0.5:
        return 0
    else:
        return 1
        
X=np.array([0.1,0.2,0.6,0.5,0.01,1])
print(f(X))

This code gives an error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

but I don't know how a.any() or a.all() will be useful for me. I want the output to be:-

[0,0,1,0,0,1]

I can use the for loop, but is there any shortcut syntax so that I get the desired output in just one go?

1
  • 2
    The easiest would be np.where(X<=0.5, 0, 1). See the docs here. Commented Aug 15, 2020 at 8:26

1 Answer 1

0

You can use vectorize - https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html

In [1]: import numpy as np

In [2]: X=np.array([0.1,0.2,0.6,0.5,0.01,1])

In [3]: f = lambda x: 0 if x<=0.5 else 1

In [4]: func = np.vectorize(f)

In [5]: func(X)
Out[5]: array([0, 0, 1, 0, 0, 1])

OR

where - https://numpy.org/doc/stable/reference/generated/numpy.where.html

In [7]: np.where(X<=0.5, 0,1)
Out[7]: array([0, 0, 1, 0, 0, 1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.