在 NumPy 中按元素新增不同形狀的引數


要按元素新增不同形狀的引數,請在 Python NumPy 中使用 **numpy.add()** 方法。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.add() 方法 -

print("
Result (adding 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 add arguments element-wise with different shapes, use the numpy.add() method in Python Numpy print("
Result (adding 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 (adding 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.]]]

更新於: 2022年2月7日

489 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告