2014-11-06 24 views
1

我有不同形狀的numpy陣列的numpy.array。 當我打電話np.sum(my_array)我得到這個錯誤:總結所有來自陣列內不同形狀的numpy子陣列的所有值

Traceback (most recent call last): 
return umr_sum(a, axis, dtype, out, keepdims) 
ValueError: operands could not be broadcast together with shapes (13,5) (5,3) 

所有我想要的是在所有陣列狀總和(my_array)所有值之和=一些浮點數

有一些參數我錯過了還是另一種方法? 我只能想到這樣的事情

np.sum([np.sum(a) for a in my_array]) 

這是一個最佳的方法是什麼?

更新:

print(type(my_array)) 
print((my_array).shape) 
print([(type(sub_array), sub_array.shape) for sub_array in my_array]) 

輸出:

<class 'numpy.ndarray'> 
(2,) 
[(<class 'numpy.ndarray'>, (13, 5)), (<class 'numpy.ndarray'>, (5, 3))] 
+0

什麼是my_array?它是一個包含numpy數組的Python列表嗎? – jozzas 2014-11-06 21:30:25

+0

@jozzas這也是一個numpy.array – userqwerty1 2014-11-06 21:32:48

+0

這是什麼樣的ndarray包含不同形狀的其他ndarrays?請爲我們打印'type(my_array)'的結果。 – ballsatballsdotballs 2014-11-06 21:35:16

回答

4

使用發電機應在大多數情況下更好地:

np.sum(np.sum(a) for a in my_array) 

沒有 '[...]'你不會創建一個列表。

%timeit np.sum(np.sum(a) for a in my_array) 

100000循環,最好的3:每圈5.73微秒

%timeit np.sum([np.sum(a) for a in my_array]) 

100000循環,最好的3:每圈9.97微秒

+0

哇。不知道我可以省略'[..]'謝謝。你如何做出這個時間?我已經嘗試過但不能像你的那樣工作。請,你能告訴或發佈鏈接嗎? – userqwerty1 2014-11-06 22:04:00

+1

我在一個IPython Notebook中寫了這個。你應該看看這個,它包含在安裝帶有anaconda或enthougt的python時。 %timeit可以在那裏使用。 – espang 2014-11-06 22:08:08

+0

哇。尼斯。謝謝。 – userqwerty1 2014-11-06 22:12:06

0
a = np.array(map(np.arange, range(16, 32))) 

Eyy![28]: %timeit np.sum(map(np.sum, a)) 
10000 loops, best of 3: 90.5 µs per loop 

Eyy![29]: %timeit np.sum(np.sum(b) for b in a) 
10000 loops, best of 3: 86 µs per loop 

Eyy![30]: %timeit np.sum([np.sum(b) for b in a]) 
10000 loops, best of 3: 90.2 µs per loop 

也注意到,它可以多次如果您事先知道最大尺寸,則更容易擁有零填充的numpy陣列。

相關問題