Python Numpy recarray.flatten()函数
在numpy中,数组可以有一个包含字段的数据类型,类似于电子表格中的列。一个例子是[(a, int), (b, float)] ,其中数组中的每个条目是一对(int, float)。通常情况下,这些属性使用字典查询,如arr[‘a’] 和 arr[‘b’] 。记录数组允许字段作为数组的成员被访问,使用arr.a和arr.b。
numpy.recarray.flatten()函数返回单维的记录数组。
语法: numpy.recarray.flatten(order='C')
参数:
order : [[‘C’, ‘F’, ‘A’, ‘K’], 可选]
‘C’意味着按行大调(C式)的顺序进行平移。
F “是指以列主语(Fortran-风格)的顺序进行扁平化。
‘A’意味着如果a在内存中是连续的,就以列为主的顺序进行平移,否则以行为主的顺序进行平移。
K’意味着按照元素在内存中出现的顺序进行平移。默认是’C’。
返回 : 一个输入数组的副本,被压扁为一维。
代码#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]