错误的解决方案:具有多个元素的数组的真值不明确.使用a.any()或a.all() [英] Solution to Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

查看:336
本文介绍了错误的解决方案:具有多个元素的数组的真值不明确.使用a.any()或a.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,其中使用条件 if 语句计算两个浮点值,以显示如下所示的返回值:

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

最初,我遇到了标题错误.我已经尝试过使用np.any()和np.all(),如错误和问题所建议的那样,没有运气.我正在寻找一种方法来显式分析从if语句 if z> 0 生成的布尔数组的每个元素(例如,列表w/2个元素的[True,False]),即使它是偶数可能的.如果我使用 np.any(),则在输入列表不是这种情况下,它将始终返回value1.我的问题类似于

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.

推荐答案

下面是一个简单的示例:

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

可以用TrueFalse索引多个Numpy数组,这也可以覆盖这些索引中保存的值.

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

注意:b.copy()很重要,因为在其他方面,您在b中的条目也会更改. (最好是在没有copy()的情况下尝试一次,然后查看b

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

这篇关于错误的解决方案:具有多个元素的数组的真值不明确.使用a.any()或a.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆