在NumPy中逐元素相加引數並在不同型別中顯示結果


要逐元素相加引數,請在Python NumPy中使用**numpy.add()**方法。使用“**dtype**”引數將輸出設定為“**float**”。

out是儲存結果的位置。如果提供,則其形狀必須與輸入廣播到的形狀相同。如果未提供或為None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

條件在輸入上進行廣播。在條件為True的位置,out陣列將設定為ufunc結果。在其他地方,out陣列將保留其原始值。請注意,如果透過預設的out=None建立未初始化的out陣列,則其中條件為False的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫:

import numpy as np

建立兩個包含int元素的二維陣列:

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)

要逐元素相加引數,請在Python NumPy中使用numpy.add()方法。使用“dtype”引數將輸出設定為“float”:

print("
Result (adding element-wise)...
",np.add(arr1, arr2, dtype = 'float'))

示例

import numpy as np

# Create two 2D arrays with int elements
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 add arguments element-wise, use the numpy.add() method in Python Numpy # The output is set "float" using the "dtype" parameter print("
Result (adding element-wise)...
",np.add(arr1, arr2, dtype = 'float'))

輸出

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 (adding element-wise)...
[[12. 24. 36.]
[53. 65. 91.]]

更新於:2022年2月7日

275 次檢視

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告