在 Numpy 中返回一個二維陣列,其上對角線為 1,其他位置為 0


numpy.eye() 函式返回一個二維陣列,對角線上的元素為 1,其他位置的元素為 0。這裡,第一個引數表示“輸出中的行數”,例如 4 表示 4x4 陣列。第二個引數是輸出中的列數。如果為 None,則預設為第一個引數,即這裡為 4x4。第三個引數即 K 是對角線的索引:0(預設值)表示主對角線,正值表示上對角線,負值表示下對角線。我們已使用正值 K 設定了上對角線。

eye() 函式返回一個數組,其中所有元素都等於零,除了第 k 個對角線,其值等於 1。dtype 是返回陣列的資料型別。order 指示輸出是否應以行主序(C 樣式)或列主序(Fortran 樣式)儲存在記憶體中。

like 引數是一個參考物件,允許建立不是 NumPy 陣列的陣列。如果作為 like 傳入的類陣列支援 __array_function__ 協議,則結果將由其定義。在這種情況下,它確保建立與透過此引數傳入的類陣列相容的陣列物件。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個二維陣列。numpy.eye() 返回一個二維陣列,對角線上的元素為 1,其他位置的元素為 0。第三個引數即 K 是對角線的索引:0(預設值)表示主對角線,正值表示上對角線,負值表示下對角線。我們已使用正值 K 設定了上對角線 -

arr = np.eye(4, k = 1)

顯示陣列 -

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
# The numpy.eye() returns a 2-D array with 1’s as the diagonal and 0’s elsewhere.
# Here, the 1st parameter means the "Number of rows in the output" i.e. 4 means 4x4 array
# The 2nd parameter is the number of columns in the output. If None, defaults to the 1st parameter i.e. 4x4 here.
# The 3rd parameter i.e. K is the Index of the diagonal: 0 (the default) refers to the main diagonal,
# a positive value refers to an upper diagonal,
# and a negative value to a lower diagonal.
# We have set the upper diagonal with a positive value K
arr = np.eye(4, k = 1)

# 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...
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]

Array type...
float64

Array shape...
(4, 4)

Array Dimensions...
2

Array (count of elements)...
16

更新於: 2022年2月10日

114 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告