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

前提是你 提交于 2019-12-11 06:25:08

问题


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.


回答1:


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




回答2:


If z is an array

  z=value2-value1
  if np.any(z>0):
     return value1
  elif z<0:
     return value2

z>0 and z<0 will be boolean arrays. np.any(z>0) reduces that array to one True/False value, which works in the if statement. But the z<0 is still multivalued, and with give elif a headache.



来源:https://stackoverflow.com/questions/45407651/solution-to-error-the-truth-value-of-an-array-with-more-than-one-element-is-amb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!