從 Numpy 中的二進位制資料建立記錄陣列
若要從二進位制資料建立記錄陣列,請在 Python Numpy 中使用 numpy.core.records.fromstring() 方法。我們將 tobytes() 方法用於二進位制資料。
第一個引數是 datastring 即二進位制資料的緩衝區。此函式返回 datastring 中資料的記錄陣列檢視。如果 datastring 為只讀,則此檢視將為只讀。offset 引數是開始讀取緩衝區的該位置。如果 dtype 為 None,則 formats、names、titles、aligned、byteorder 引數將傳遞到 numpy.format_parser 以構造一個 dtype。
步驟
首先,匯入所需的庫 −
import numpy as np
設定陣列型別 −
my_type = [('Team', (np.str_, 10)), ('Points', np.float64),('Rank', np.int32)]
輸出陣列 −
print("Record Array types...
",my_type)使用 numpy.array() 方法建立陣列 −
arr = np.array([('AUS', 115, 5), ('NZ', 125, 3),('IND', 150, 1)], dtype=my_type)
輸出陣列 −
print("
Array...
",arr)若要從二進位制資料建立記錄陣列,請使用 numpy.core.records.fromstring() 方法。我們已經使用 tobytes() 方法用於二進位制資料 −
rec = np.core.records.fromstring(arr.tobytes(), dtype=my_type)
print("
Record Array...
",rec)示例
import numpy as np
# Set the array type
my_type = [('Team', (np.str_, 10)), ('Points', np.float64),('Rank', np.int32)]
# Display the type
print("Record Array types...
",my_type)
# Create an array using the numpy.array() method
arr = np.array([('AUS', 115, 5), ('NZ', 125, 3),('IND', 150, 1)], dtype=my_type)
# Display the array
print("
Array...
",arr)
# To create a record array from binary data, use the numpy.core.records.fromstring() method in Python Numpy
# We have used the tobytes() method for binary data
rec = np.core.records.fromstring(arr.tobytes(), dtype=my_type)
print("
Record Array...
",rec)輸出
Record Array types...
[('Team', (<class 'numpy.str_'>, 10)), ('Points', <class 'numpy.float64'>), ('Rank', <class 'numpy.int32'>)]
Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)]
Record Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP