在 NumPy 中返回單位陣列並更改輸出的資料型別


要返回單位陣列,請在 Python NumPy 中使用 **numpy.identity()** 方法。單位陣列是一個正方形陣列,主對角線上為 1。1s 引數是 n x n 輸出中行(和列)的數量。“**dtype**”引數用於返回輸出的資料型別。

該函式返回一個 n x n 陣列,其主對角線設定為 1,所有其他元素為 0。like 引數是一個參考物件,允許建立不是 NumPy 陣列的陣列。如果作為 like 傳入的類陣列支援 __array_function__ 協議,則結果將由它定義。在這種情況下,它確保建立與透過此引數傳入的陣列物件相容的陣列物件。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個 2d 陣列。要返回單位陣列,請在 Python NumPy 中使用 numpy.identity() 方法。“dtype”引數用於返回輸出的資料型別 -

arr = np.identity(4, dtype = int)

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

print("
Array type...
", arr.dtype)

獲取陣列的形狀 -

print("
Array shape...
", arr.shape)

獲取陣列的維度 -

print("
Array Dimensions...
",arr.ndim)

獲取陣列中元素的數量 -

print("
Array (count of elements)...
",arr.size)

示例

import numpy as np

# Create a 2d array
# To return the identity array, use the numpy.identity() method in Python Numpy
# The identity array is a square array with ones on the main diagonal.
# The 1s parameter is the number of rows (and columns) in n x n output
# The "dtype" parameter is used to return the ata-type of the output.
arr = np.identity(4, dtype = int)

# Display the array
print("Array...
", arr) # Get the type of the array print("
Array type...
", arr.dtype) # Get the shape of the array print("
Array shape...
", arr.shape) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the number of elements of the Array print("
Array (count of elements)...
",arr.size)

輸出

Array...
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]

Array type...
int64

Array shape...
(4, 4)

Array Dimensions...
2

Array (count of elements)...
16

更新於: 2022年2月10日

107 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告