在NumPy中按元素劃分引數並以不同型別顯示結果


要按元素劃分引數,請在Python NumPy中使用**numpy.divide()**方法。arr1被視為被除數陣列。arr2被視為除數陣列。使用“**dtype**”引數將輸出設定為“**float**”。

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

NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援廣泛的硬體和計算平臺,並且與分散式、GPU和稀疏陣列庫配合良好。

步驟

首先,匯入所需的庫:

import numpy as np

建立兩個二維陣列:

arr1 = np.array([[14, 28, 56], [84, 56, 112]])
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.divide()方法。arr1被視為被除數陣列。arr2被視為除數陣列。使用“dtype”引數將輸出設定為“float”。

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

示例

import numpy as np

# Create two 2D arrays
arr1 = np.array([[14, 28, 56], [84, 56, 112]])
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 divide arguments element-wise, use the numpy.divide() method in Python Numpy # The arr1 is considered Dividend array # The arr2 is considered Divisor array # The output is set "float" using the "dtype" parameter print("
Result (divide element-wise)...
",np.divide(arr1, arr2, dtype = 'float'))

輸出

Array 1...
[[ 14 28 56]
[ 84 56 112]]

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 (divide element-wise)...
[[2. 2. 2.66666667]
[3. 1.6 2. ]]

更新於:2022年2月7日

317 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告