numpy recarray.flatten()函数| Python
在 numpy 中,数组可能具有包含字段的数据类型,类似于电子表格中的列。一个例子是[(a, int), (b, float)]
,其中数组中的每个条目都是一对 (int, float)。通常,使用诸如arr['a'] and arr['b']
类的字典查找来访问这些属性。记录数组允许使用arr.a and arr.b
作为数组成员访问字段。
numpy.recarray.flatten()
函数返回一维记录数组。
Syntax : numpy.recarray.flatten(order='C')
Parameters:
order : [[‘C’, ‘F’, ‘A’, ‘K’], optional]
‘C’ means to flatten in row-major (C-style) order.
‘F’ means to flatten in column-major (Fortran- style) order.
‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.
‘K’ means to flatten in the order the elements occur in memory. The default is ‘C’.
Return : A copy of the input array, flattened to one dimension.
Code #1 :
# Python program explaining
# numpy.recarray.flatten() method
# importing numpy as geek
import numpy as geek
# creating input array with 2 different field
in_arr = geek.array([[(5.0, 2), (3.0, -4), (6.0, 9)],
[(9.0, 1), (5.0, 4), (-12.0, -7)]],
dtype =[('a', float), ('b', int)])
print ("Input array : ", in_arr)
# convert it to a record array,
# using arr.view(np.recarray)
rec_arr = in_arr.view(geek.recarray)
print("Record array of float: ", rec_arr.a)
print("Record array of int: ", rec_arr.b)
# applying recarray.flatten methods
# to float record in Fortan order
out_arr1 = rec_arr.a.flatten(order ='F')
print ("Output float flattened array in Fortan order: ", out_arr1)
# applying recarray.flatten methods
# to float record array in default order
out_arr2 = rec_arr.a.flatten()
print ("Output float flattenedarray in default order : ", out_arr2)
# applying recarray.flatten methods
# to int record in 'A' order
out_arr3 = rec_arr.b.flatten(order ='A')
print ("Output int flattened array in A order: ", out_arr3)
# applying recarray.flatten methods
# to float record array in 'K' order
out_arr4 = rec_arr.b.flatten(order ='K')
print ("Output intt flattened array in K order : ", out_arr4)
Input array : [[( 5., 2) ( 3., -4) ( 6., 9)]
[( 9., 1) ( 5., 4) (-12., -7)]]
Record array of float: [[ 5. 3. 6.]
[ 9. 5. -12.]]
Record array of int: [[ 2 -4 9]
[ 1 4 -7]]
Output float flattened array in Fortan order: [ 5. 9. 3. 5. 6. -12.]
Output float flattenedarray in default order : [ 5. 3. 6. 9. 5. -12.]
Output int flattened array in A order: [ 2 -4 9 1 4 -7]
Output intt flattened array in K order : [ 2 -4 9 1 4 -7]