Python 使用numpy对另一个数组中的条件数组求和

Python 使用numpy对另一个数组中的条件数组求和,python,arrays,numpy,Python,Arrays,Numpy,我有下面的python代码来求一个数组与另一个数组中的条件之和 sum=0 for i in range(grp_num): if lower_bounds[i] > 0: sum = sum + histo1[i] 我相信numpy等价物应该是np.where(下限>0,histor1,0).sum() 但是numpy方法将histo1中的所有内容相加(忽略下限>0的要求)。为什么?还是有其他方法可以做到这一点?谢谢。好的,这当然是猜测,但我能想到的关于你的np

我有下面的python代码来求一个数组与另一个数组中的条件之和

sum=0
for i in range(grp_num):
    if lower_bounds[i] > 0:
        sum = sum + histo1[i]
我相信numpy等价物应该是
np.where(下限>0,histor1,0).sum()

但是numpy方法将histo1中的所有内容相加(忽略下限>0的要求)。为什么?还是有其他方法可以做到这一点?谢谢。

好的,这当然是猜测,但我能想到的关于你的
np.where(lower_bounds>0,Histor1,0).sum()返回完整总和的唯一解释是

  • 你在练蟒蛇
  • 下界是一个列表,而不是数组
关于Python2:

[1, 2] > 0
True

这意味着您的numpy行将广播其第一个参数,并始终从histor1中选择,而不是从0中选择。请注意,在这种情况下,注释
histo1[lower_bounds>0].sum()中建议的替代公式也将不起作用(它将返回
histo1[1]

解决方案。显式地将下界转换为数组

 np.where(np.array(lower_bounds)>0, histo1, 0)
顺便说一句,在Python3上你会得到一个异常

[1, 2] > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'list' and 'int'
[1,2]>0
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“list”和“int”的实例之间不支持“>”

好吧,这当然是猜测,但我能想到的唯一解释是关于你的
np.where(下限>0,histor1,0).sum()
返回完整的和

  • 你在练蟒蛇
  • 下界是一个列表,而不是数组
关于Python2:

[1, 2] > 0
True

这意味着您的numpy行将广播其第一个参数,并始终从histor1中选择,而不是从0中选择。请注意,在这种情况下,注释
histo1[lower_bounds>0].sum()中建议的替代公式也将不起作用(它将返回
histo1[1]

解决方案。显式地将下界转换为数组

 np.where(np.array(lower_bounds)>0, histo1, 0)
顺便说一句,在Python3上你会得到一个异常

[1, 2] > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'list' and 'int'
[1,2]>0
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“list”和“int”的实例之间不支持“>”

histor1[lower\u bounds>0]。sum()
histor1[lower\u bounds>0]。sum()
关于Python 2和列表,您是对的!作为Python的初学者,我对数据结构不太熟悉。谢谢。你说得对(关于Python 2和列表)!作为Python的初学者,我对数据结构不太熟悉。谢谢