Programmers learn & share
0 votes
667 views

Problem :

I got following rather cryptic error message:
the truth value of an array with more than one element is ambiguous. use a.any() or a.all()
by (6.9k points)   | 667 views

2 Answers

0 votes

Solution :

I had the same problem with indexing with multiple-conditions while finding the data in a certain date range. The (a-b).any() OR (a-b).all() was not working for me at all.

I found the solution which works perfectly for my functionality. 

Simply used the numpy.logical_and(a,b) and it worked for me. Following is the way to rewrite the code :

selected  = r[numpy.logical_and(r["dt"] >= startdate, r["dt"] <= enddate)]
by (36.1k points)  
0 votes

The error message explains itself very well.

ValueError: The truth value of an array with more than one element is ambiguous.

Use a.any() or a.all().

Solutions:

Array comparison return boolean:

Make sure your array comparison returns a boolean array. Methods any() and all() reduce values over the array either the value is logical_or or logical_and. Probably you also don’t need to check for equality.

What should bool return?

The main question is what should the bool(np.array([False, False, True])) have to return. There are many arguments.

  • True, because bool(np.array(x)) should have to return same as bool(list(x)), and non empty lists.
  • True, Because at least one element has to be true.
  • False, because all the elements are not false value.

Since, the truth value of an array having more than one element is ambiguous so you have to use .any() or .all().

Example:

>>> v = np.array([1, 2, 3]) == np.array([1, 2, 4])

>>> v

Array([True, True, False], dtype=bool)

>>> v.any()

True

>>> v.all()

False

Float values:

You have to use np.allclose, if you are making comparisons of array for float data type.

Example:

>>> np.allclose(np.array([1, 2, 3_1e-8]), np.array([1, 2, 3]))

True.

I hope you can understand and this answer will help to solve your problem.

by (2.5k points)  
2,220 questions
2,690 answers
59 comments
241 users