从NumPy中的(扁平)数组列表创建记录数组


要从(扁平)数组列表创建记录数组,请在Python NumPy中使用**numpy.core.records.fromarrays()**方法。它返回由给定arrayList列组成的记录数组。

第一个参数是数组状对象的列表(例如列表、元组和ndarray)。dtype是所有数组的有效dtype。如果dtype为None,则formats、names、titles、aligned、byteorder参数将传递给numpy.format_parser以构造dtype。

步骤

首先,导入所需的库:

import numpy as np

使用numpy.array()方法创建一个新数组:

arr1 = np.array([[5, 10, 15], [20, 25, 30]])
arr2 = np.array([[9, 18, 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()方法:

print("
Record Array...
",np.core.records.fromarrays([arr1,arr2,arr3]))

示例

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, 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 print("
Record Array...
",np.core.records.fromarrays([arr1,arr2,arr3]))

输出

Array1...
[[ 5 10 15]
[20 25 30]]
Array2...
[[ 9. 18. 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

更新于:2022年2月17日

254 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.