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

Dung Do Tien Aug 23 2021 185

Hi Guys, I have an array in Python 3.8.2 and I want to check all items of it.

If the item is odd number -> return false and it's even number -> return true:

import numpy as np
ageData = [12, 15, 19, 24, 27, 35, 46, 58, 63, 78, 81]
ageArray = np.array(ageData)

print(bool(ageArray % 2))

I want to return from 

[12, 15, 19, 24, 27, 35, 46, 58, 63, 78, 81]

 to

[true, false, false, true, false, false, true, true, false, true, false]

But when I run code I get an error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(bool(ageArray % 2))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Pls help me what is it? and how can I resolve it?

Thanks!

Have 1 answer(s) found.
  • J

    Jose Luis Aug 23 2021

    You can not use bool() method to help convert true/false conditions. You can see code bellow:

    import numpy as np
    ageData = [12, 15, 19, 24, 27, 35, 46, 58, 63, 78, 81]
    ageArray = np.array(ageData)
    
    boolArr = (ageArray % 2) <= 0
    print(boolArr)

    #Output

    [True False False  True False False  True  True False  True False]

    It's so easy!!  I hope it helpful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close