Skip to content
Related Articles

Related Articles

Numpy recarray.flatten() function | Python

Improve Article
Save Article
  • Last Updated : 29 Nov, 2022
Improve Article
Save Article

In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr[‘a’] and arr[‘b’]. Record arrays allow the fields to be accessed as members of the array, using arr.a and arr.b. numpy.recarray.flatten() function returns record arrays in one dimension.

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 : 

Python3




# 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 Fortran order
out_arr1 = rec_arr.a.flatten(order ='F')
print ("Output float flattened array in Fortran 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)

Output:

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]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!