從(扁平)陣列列表建立記錄陣列並在 NumPy 中為所有陣列設定有效的資料型別
要從(扁平)陣列列表建立記錄陣列,請在 Python NumPy 中使用 **numpy.core.records.fromarrays()** 方法。資料型別使用 **"dtype"** 引數設定。
它返回包含給定 arrayList 列的記錄陣列。第一個引數是陣列類物件(例如列表、元組和 ndarrays)的列表。dtype 是所有陣列的有效 dtype。如果 dtype 為 None,則格式、名稱、標題、對齊、位元組序引數將傳遞給 numpy.format_parser 以構造 dtype。
步驟
首先,匯入所需的庫 -
import numpy as np
使用 numpy.array() 方法建立一個新陣列 -
arr1 = np.array([[5, 10, 15], [20, 25, 30]]) arr2 = np.array([[9, 18.8, 24], [87.5, 65, 23.8]]) arr3 = np.array([['12', 'bbb', 'john'], ['5.6', '29', 'k']])
顯示陣列 -
print("Array1...
",arr1)
print("Array2...
",arr2)
print("Array3...
",arr3)獲取陣列的型別 -
print("
Array1 type...
", arr1.dtype)
print("
Array2 type...
", arr2.dtype)
print("
Array3 type...
", arr3.dtype)獲取陣列的維度 -
print("
Array1 Dimensions...
", arr1.ndim)
print("
Array2 Dimensions...
", arr2.ndim)
print("
Array3 Dimensions...
", arr3.ndim)要從(扁平)陣列列表建立記錄陣列,請在 Python NumPy 中使用 numpy.core.records.fromarrays() 方法。資料型別使用“dtype”引數設定 -
rec = np.core.records.fromarrays([arr1,arr2,arr3], dtype=np.dtype([('a', np.int32), ('b', np.float32),
('c','S3' )]))
print("
Record Array...
",rec)示例
import numpy as np
# Create a new array using the numpy.array() method
arr1 = np.array([[5, 10, 15], [20, 25, 30]])
arr2 = np.array([[9, 18.8, 24], [87.5, 65, 23.8]])
arr3 = np.array([['12', 'bbb', 'john'], ['5.6', '29', 'k']])
# Display the arrays
print("Array1...
",arr1)
print("Array2...
",arr2)
print("Array3...
",arr3)
# Get the type of the arrays
print("
Array1 type...
", arr1.dtype)
print("
Array2 type...
", arr2.dtype)
print("
Array3 type...
", arr3.dtype)
# Get the dimensions of the Arrays
print("
Array1 Dimensions...
", arr1.ndim)
print("
Array2 Dimensions...
", arr2.ndim)
print("
Array3 Dimensions...
", arr3.ndim)
# To create a record array from a (flat) list of array, use the numpy.core.records.fromarrays() method in Python Numpy
# The datatype is set using the "dtype" parameter
rec = np.core.records.fromarrays([arr1,arr2,arr3],
dtype=np.dtype([('a', np.int32), ('b', np.float32), ('c','S3' )]))
print("
Record Array...
",rec)輸出
Array1... [[ 5 10 15] [20 25 30]] Array2... [[ 9. 18.8 24. ] [87.5 65. 23.8]] Array3... [['12' 'bbb' 'john'] ['5.6' '29' 'k']] Array1 type... int64 Array2 type... float64 Array3 type... <U4 Array1 Dimensions... 2 Array2 Dimensions... 2 Array3 Dimensions... 2 Record Array... [[( 5, 9. , b'12') (10, 18.8, b'bbb') (15, 24. , b'joh')] [(20, 87.5, b'5.6') (25, 65. , b'29') (30, 23.8, b'k')]]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP