NumPy中不同形狀陣列的元素級乘法
要在Python NumPy中對不同形狀的引數進行元素級乘法,請使用**numpy.multiply()**方法。
out是一個儲存結果的位置。如果提供,它必須具有輸入廣播到的形狀。如果沒有提供或為None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。
條件在輸入上廣播。在條件為True的位置,out陣列將設定為ufunc結果。在其他位置,out陣列將保留其原始值。請注意,如果透過預設的out=None建立一個未初始化的out陣列,則其中條件為False的位置將保持未初始化狀態。
NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且與分散式、GPU和稀疏陣列庫配合良好。
步驟
首先,匯入所需的庫:
import numpy as np
建立兩個不同形狀的陣列:
arr1 = np.arange(27.0).reshape((3, 3, 3)) arr2 = np.arange(9.0).reshape((3, 3))
顯示陣列:
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)
要在Python NumPy中對不同形狀的引數進行元素級乘法,請使用numpy.multiply()方法:
print("
Result (multiply element-wise)...
",np.multiply(arr1, arr2))
示例
import numpy as np # Create two arrays with different shapes arr1 = np.arange(27.0).reshape((3, 3, 3)) arr2 = np.arange(9.0).reshape((3, 3)) # 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 multiply arguments element-wise with different shapes, use the numpy.multiply() method in Python Numpy print("
Result (multiply element-wise)...
",np.multiply(arr1, arr2))
輸出
Array 1... [[[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] [[ 9. 10. 11.] [12. 13. 14.] [15. 16. 17.]] [[18. 19. 20.] [21. 22. 23.] [24. 25. 26.]]] Array 2... [[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]] Our Array 1 type... float64 Our Array 2 type... float64 Our Array 1 Dimensions... 3 Our Array 2 Dimensions... 2 Our Array 1 Shape... (3, 3, 3) Our Array 2 Shape... (3, 3) Result (multiply element-wise)... [[[ 0. 1. 4.] [ 9. 16. 25.] [ 36. 49. 64.]] [[ 0. 10. 22.] [ 36. 52. 70.] [ 90. 112. 136.]] [[ 0. 19. 40.] [ 63. 88. 115.] [144. 175. 208.]]]
廣告