Search code examples
arrayspython-3.xnumpyboolean-operations

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


I have a function where I'm calculating two float values with a conditional if statement for the return values shown below:

 # The function inputs are 2 lists of floats
 def math(list1,list2):
  value1=math(...)
  value2=more_math(...)
  z=value2-value1
  if np.any(z>0):
     return value1
  elif z<0:
     return value2

Initially, I ran into the title error. I have tried using np.any() and np.all() as suggested by the error and questions here with no luck. I am looking for a method to explicitly analyze each element of the boolean array (e.g. [True,False] for list w/ 2 elements) generated from the if statement if z>0, if it is even possible. If I use np.any(), it is consistently returning value1 when that is not the case for the input lists. My problem is similar to The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()? but it went unanswered.


Solution

  • Here's a simple example:

    a = np.array([1,2,3,4]) #for simplicity
    b = np.array([0,0,5,5])
    c = b.copy() 
    condition = a>b  #returns an array with True and False, same shape as a
    c[condition] = a[condition] #copy the values of a into c
    

    Numpy arrays can be indexed by True and False, which also allows to overwirte the values saved in these indeces.

    Note: b.copy() is important, because other wise your entries in bwill change as well. (best is you try it once without the copy() and then have a look at what happens at b