在 Numpy 中建立二維陣列,並將扁平化的輸入作為下對角線


要建立二維陣列,並將扁平化的輸入作為對角線,可以使用 Python Numpy 中的 **numpy.diagflat()** 方法。'K 引數用於設定對角線;0(預設值)對應於“主”對角線,負 k 表示主對角線下方第 k 條對角線。

第一個引數是輸入資料,該資料被展平並設定為輸出的第 k 條對角線。第二個引數是要設定的對角線;0(預設值)對應於“主”對角線,正(負)k 表示主對角線上方(下方)第 k 條對角線。

NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且可以很好地與分散式、GPU 和稀疏陣列庫配合使用。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 numpy.array() 方法建立 2D 陣列 -

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() 方法建立二維陣列,並將扁平化的輸入作為對角線。'K 引數用於設定對角線;0(預設值)對應於“主”對角線,負 k 表示主對角線下方第 k 條對角線 -

print("
Result...
",np.diagflat(arr, k = -1))

示例

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, k = -1))

輸出

Array...
[[ 5 10]
[15 20]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(2, 2)

Elements in the Array...
4

Result...
[[ 0 0 0 0 0]
[ 5 0 0 0 0]
[ 0 10 0 0 0]
[ 0 0 15 0 0]
[ 0 0 0 20 0]]

更新於: 2022年2月16日

100 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告