返回一個對角線為1,其他位置為0的二維陣列,但在Numpy中設定不同的資料型別
**numpy.eye()** 函式返回一個二維陣列,對角線上的元素為 1,其他位置的元素為 0。這裡,第一個引數表示“輸出的行數”,例如 4 表示 4x4 陣列。第二個引數是輸出的列數。如果為 None,則預設為第一個引數,這裡為 4x4。**dtype** 引數用於設定返回陣列的不同資料型別。
eye() 函式返回一個數組,其中所有元素都等於零,除了第 k 個對角線上的元素,其值為 1。dtype 是返回陣列的資料型別。order 指定輸出是否應以行主序(C 樣式)或列主序(Fortran 樣式)儲存在記憶體中。
like 引數是一個引用物件,允許建立不是 NumPy 陣列的陣列。如果作為 like 傳入的類陣列支援 __array_function__ 協議,則結果將由它定義。在這種情況下,它確保建立與透過此引數傳入的類陣列相容的陣列物件。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個二維陣列。numpy.eye() 返回一個二維陣列,對角線上的元素為 1,其他位置的元素為 0。這裡,第一個引數表示“輸出的行數”,例如 4 表示 4x4 陣列。第二個引數是輸出的列數。如果為 None,則預設為第一個引數,這裡為 4x4。**dtype** 引數用於設定返回陣列的不同資料型別 -
arr = np.eye(4, dtype = float)
顯示陣列 -
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.
# The "dtype" parameter is used to set a different datatype of the returned array
arr = np.eye(4, dtype = float)
# 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... float64 Array shape... (4, 4) Array Dimensions... 2 Array (count of elements)... 16
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP