NumPy中不同形狀陣列的元素級相減


要對不同形狀的引數進行逐元素相減,請在Python NumPy中使用**numpy.subtract()**方法。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)

獲取陣列的維度:

Get the dimensions of the Arrays:

獲取陣列的形狀:

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

要對不同形狀的引數進行逐元素相減,請在Python NumPy中使用numpy.subtract()方法:

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

[[ 9. 9. 9.]
[ 9. 9. 9.]
[ 9. 9. 9.]]

[[18. 18. 18.]
[18. 18. 18.]
[18. 18. 18.]]]

更新於:2022年2月7日

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告