將輸入解釋為 NumPy 中的矩陣


要將輸入解釋為矩陣,請在 Python NumPy 中使用 **numpy.asmatrix()** 方法。與矩陣不同,如果輸入已經是矩陣或 ndarray,則 asmatrix 不會建立副本。等效於 matrix(data, copy=False)。

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

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個二維陣列 -

arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])

顯示我們的陣列 -

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)

要將輸入解釋為矩陣,請在 Python NumPy 中使用 numpy.asmatrix() 方法 -

res = np.asmatrix(arr)
print("
Result...
",res)

設定一些值 -

arr[0,2] = 99
arr[1,1] = 199
arr[2,1] = 299

顯示更新後的矩陣 -

print("
Updated Matrix...
",arr)

示例

import numpy as np

# Create a 2d array
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])

# 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 Interpret the input as a matrix, use the numpy.asmatrix() method in Python Numpy res = np.asmatrix(arr) print("
Result...
",res) # Set some values arr[0,2] = 99 arr[1,1] = 199 arr[2,1] = 299 # Display the updated matrix print("
Updated Matrix...
",arr)

輸出

Array...
[[36 36 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

Result...
[[36 36 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Updated Matrix...
[[ 36 36 99 88]
[ 92 199 98 45]
[ 22 299 54 69]
[ 69 80 80 99]]

更新於: 2022年2月17日

263 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告