使用Numpy建立二維陣列,並將扁平化輸入作為對角線
要建立一個以扁平化輸入作為對角線的二維陣列,可以使用Python Numpy中的**numpy.diagflat()**方法。第一個引數是輸入資料,它會被扁平化並設定為輸出的第k個對角線。第二個引數是要設定的對角線;預設值為0,對應於“主”對角線,正(負)k表示高於(低於)主對角線的對角線數。
NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且可以很好地與分散式、GPU和稀疏陣列庫配合使用。
步驟
首先,匯入所需的庫:
import numpy as np
使用numpy.array()方法建立一個二維陣列:
arr = np.array([[5, 10], [15, 20]])
顯示我們的陣列:
print("Array...
",arr)獲取資料型別:
print("
Array datatype...
",arr.dtype)
獲取陣列的維度:
print("
Array Dimensions...
",arr.ndim)獲取陣列的形狀:
print("
Our Array Shape...
",arr.shape)獲取陣列的元素個數:
print("
Elements in the Array...
",arr.size)要建立一個以扁平化輸入作為對角線的二維陣列,可以使用numpy.diagflat()方法:
print("
Result...
",np.diagflat(arr))
示例
import numpy as np
# Create a 2D array using the numpy.array() method
arr = np.array([[5, 10], [15, 20]])
# Displaying our array
print("Array...
",arr)
# Get the datatype
print("
Array datatype...
",arr.dtype)
# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# Get the number of elements of the Array
print("
Elements in the Array...
",arr.size)
# To create a two-dimensional array with the flattened input as a diagonal, use the numpy.diagflat() method in Python Numpy
print("
Result...
",np.diagflat(arr))輸出
Array... [[ 5 10] [15 20]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (2, 2) Elements in the Array... 4 Result... [[ 5 0 0 0] [ 0 10 0 0] [ 0 0 15 0] [ 0 0 0 20]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP