numpy筆記案例之數組運算

數組運算

知識儲備

  • 數組與數的運算
    運算符可以作用到每個元素
>>> scores=[[1,2,3,4,5],[6,7,8,9,10]]
>>> scores
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
>>> test=np.array(scores)
>>> test
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> test+1#每個元素+1
array([[ 2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11]])
>>> test-1
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> test*2#每個元素*2
array([[ 2,  4,  6,  8, 10],
       [12, 14, 16, 18, 20]])
  • 數組與數組的運算
    不同形狀的數組直接運算會報錯,如下:
>>> test
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> test1=np.array([[1,2,3],[4,5,6]])
>>> test1
array([[1, 2, 3],
       [4, 5, 6]])
>>> test+test1
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    test+test1
ValueError: operands could not be broadcast together with shapes (2,5) (2,3) 

廣播機制
數組之間直接運算時,numpy會比較他們的形狀。
Numpy 可以轉換這些形狀不同的數組,使它們都具有相同的大小,然後再對它們進行運算。
只有符合下面兩個條件之一纔可以運算

  • 形狀相等(元素數量相等)
  • 維數相同,且某一個或多個維度長度爲1(其中相對應的一個地方爲1)
    在這裏插入圖片描述
  • 數組擁有極少的維度,可以在其前面追加長度爲 1 的維度,使上述條件成立(在左邊補1)
    例如
    在這裏插入圖片描述
    第二個可以理解爲1 x 1 x 3

總的來說,可以理解爲
如果數字相同或者其中一方爲1(空的可以用1代替)

>>> test
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> test1
array([[2],
       [2]])
>>> np.shape(test)
(2, 5)
>>> np.shape(test1)
(2, 1)
>>> test+test1#第一位2相等,第二位其中一方爲1
array([[ 3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12]])
>>> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章