返回一個對角線為1,其他位置為0的二維陣列,並設定NumPy中的列數
numpy.eye() 函式返回一個二維陣列,對角線元素為 1,其他元素為 0。第一個引數表示輸出陣列的行數,例如,4 表示 4x4 陣列。第二個引數表示輸出陣列的列數。
eye() 函式返回一個數組,其中所有元素都等於零,除了第 k 個對角線上的元素等於一。dtype 是返回陣列的資料型別。order 指定輸出是否應以行主序 (C 樣式) 或列主序 (Fortran 樣式) 儲存在記憶體中。
like 引數是一個參考物件,允許建立非 NumPy 陣列的陣列。如果作為 like 傳入的類陣列支援 __array_function__ 協議,則結果將由其定義。在這種情況下,它確保建立與透過此引數傳入的陣列物件相容的陣列物件。
步驟
首先,匯入所需的庫:
import numpy as np
建立一個二維陣列。numpy.eye() 返回一個二維陣列,對角線元素為 1,其他元素為 0。第一個引數表示輸出陣列的行數,例如,4 表示 4x4 陣列。第二個引數表示輸出陣列的列數。這裡我們設定為 3:
arr = np.eye(4, 3)
顯示陣列:
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. We have set 3 here arr = np.eye(4, 3) # 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. 1. 0.] [0. 0. 1.] [0. 0. 0.]] Array type... float64 Array shape... (4, 3) Array Dimensions... 2 Array (count of elements)... 12
廣告