2017-02-18 106 views
1

另一个数组,我有以下Python代码在另一个数组求和阵列与条件与numpy的

sum=0 
for i in range(grp_num): 
    if lower_bounds[i] > 0: 
     sum = sum + histo1[i] 

我认为要总结的阵列条件numpy的相当于将np.where(lower_bounds>0, histo1,0).sum() 但numpy的方法增加了一切histo1(忽略lower_bounds> 0的要求)。为什么?还是有另一种方法来做到这一点?谢谢。

+4

'histo1 [lower_bounds> 0]的.sum()' –

回答

0

好吧,这是无可否认的猜测,但我可以为你的np.where(lower_bounds>0, histo1,0).sum()返回全总和想到的唯一解释是

  • 你是Python2
  • lower_bounds是一个列表,而不是一个数组

上Python2:

[1, 2] > 0 
True 

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

解决方案。将lower_bounds明确地转换为数组

np.where(np.array(lower_bounds)>0, histo1, 0) 

Btw。在Python3,你会得到一个异常

[1, 2] > 0 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: '>' not supported between instances of 'list' and 'int' 
+0

你是对的(约Python 2和表)!作为Python的初学者,我并不关心数据结构。谢谢。 –