问题
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 b
will 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