1. 程式人生 > >理解numpy的broadcasting機制

理解numpy的broadcasting機制

最近在系統學習pandas用法,遇到了broadcasting機制,在《利用Python進行資料分析》一書中,直接翻譯成了廣播,查了下資料,整理下自己的理解微笑

參考連結:https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.

1、相同形狀
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = np.array([2.0, 2.0, 2.0])
>>> a * b
array([ 2.,  4.,  6.])
2、一個數組和一個標量值
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = 2.0
>>> a * b
array([ 2.,  4.,  6.])
上面兩種情況得到的結果相同,我們認為是b計算中作了延展,以達到和a一樣的形狀,實際上NumPy is smart enough to use the original scalar value without actually making copies,所以看起來broadcasting機制更高效。
broadcasting規則
滿足矩陣運算規則,從後向前匹配,維度相同或存在其中一個維度是1則計算