2017-02-18 102 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的初學者,我並不關心數據結構。謝謝。 –