Numpy recarray.tolist () function | python

Record arrays allow you to access fields as elements of an array using arr.a and arr.b numpy.recarray.tolist () is used to create an array as a (possibly nested) list. Returns a copy of the array data as a (nested) Python list. Items are converted to the closest compatible Python type.

Syntax: numpy.recarray.tolist()

Parameters:
None

Return: [list] The possibly nested list of array elements.

Code # 1:

# Python program explaining
# numpy.recarray.tolist () method

 
# import numy as geek

import numpy as geek

 
# create an input array with two different fields

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 an array of posts,
# 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.tolist methods
# float array of posts

out_arr = rec_arr.a.tolist ()

print ( "Output list of float record array " , out_arr) 

 
# applying recarray.tolist methods
# into an array of int records

out_arr = rec_arr.b.tolist ()

print ( "Output lis t of int record array " , out_arr) 

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 list of float record array [[5.0, 3.0, 6.0], [9.0, 5.0, -12.0]] Output list of int record array [[2, -4, 9], [ 1, 4, -7]] 

Code # 2:

We use numpy.recarray.tolist () to the entire array of records.

# Python program explaining
# numpy. recarray.tolist () method

 
# import numy as a geek

import numpy as geek

  
# create an input array with two different fields

in_arr = geek.array ([[( 5.0 , 2 ), ( 3.0 , 4 ), ( 6.0 , - 7 )],

[( 9.0 , 1 ), ( 6.0 , 4 ), ( - 2.0 , - 7 )]],

dtype = [( `a` , float ), ( `b` , int )])

  

print ( "Input array:" , in_arr)

 
# convert it to array of posts,
# using arr.view (np.recarray)

rec_arr = in_arr.view (geek.recarra y)

 
# applying recarray.tolist methods to
# write array in default order

out_arr = rec_arr.tolist ()

print ( "Output list of record array " , out_arr) 

Output:

 Input array: [[(5., 2) (3., 4) ( 6., -7)] [(9., 1) (6., 4) (-2., -7)]] Output list of record array [[(5.0, 2), (3.0, 4), ( 6.0, -7)], [(9.0, 1), (6.0, 4), (-2.0, -7)]]