使用Numpy中的廣播計算兩個向量相加


要生成模擬廣播的物件,請使用 Python Numpy 中的 **numpy.broadcast()** 方法。如果上述規則生成的結果有效,且以下條件之一為真,則稱一套陣列可廣播 −

  • 陣列的形狀完全相同。
  • 陣列的維度數相同,且每個維度的長度要麼是公共長度,要麼是 1。
  • 維度過少的陣列可以將長度為 1 的維度前置到它的形狀, ώ 使得上述所述性質為真。

步驟

首先,匯入必需的庫 −

import numpy as np

建立兩個陣列 −

arr1 = np.array([[5, 10, 15], [25, 30, 35]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

顯示陣列 −

print("Array 1...
", arr1) print("
Array 2...
", arr2)

獲取陣列的型別 −

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

獲取陣列的維度 −

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

獲取陣列的形狀 −

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要生成模擬廣播的物件,請使用 numpy.broadcast () 方法 −

x = np.broadcast(arr1, arr2)
res = np.empty(x.shape)
res.flat = [i+j for (i,j) in x]
print("
Result...
",res)

示例

import numpy as np

# Create two arrays
arr1 = np.array([[5, 10, 15], [25, 30, 35]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To produce an object that mimics broadcasting, use the numpy.add() method in Python Numpy x = np.broadcast(arr1, arr2) res = np.empty(x.shape) res.flat = [i+j for (i,j) in x] print("
Result...
",res)

輸出

Array 1...
[[ 5 10 15]
[25 30 35]]

Array 2...
[[ 7 14 21]
[28 35 56]]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result...
[[12. 24. 36.]
[53. 65. 91.]]

更新時間: 2022 年 2 月 17 日

250 次瀏覽

開始您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.