[SciPy-user] Record Array: How to add a column?

Marc Berthoud mgb11@cornell....
Mon Oct 13 19:22:26 CDT 2008


What is the best way to add a column to a record array?

Example:
Add to this array
  recarray( [ ( 'alpha' , 1 ) , ( 'beta ' , 2 ) , ( 'gamma' , 3 ) ] ,
    dtype = [ ( 'NAMES' , '|S5' ) , ( 'NR' , '>i2' ) ] )
the following column
   array( [ 3.1 ,  3.5 ,  8.1 ] )
to make that array
  recarray( [ ( 'alpha' , 1, 3.1 ), ( 'beta ' , 2 , 3.5 ) , ( 'gamma' , 
3 , 8.1 ) ] ,
    dtype = [ ( 'NAMES' , '|S5' ) , ( 'NR' , '<i2' ) , ( 'VAL' , '<f4' ) ] )
any ideas?

At this point the nicest way I know to do this is as follows:
    names = list( oldarray.dtype.names ) # get the record names
    names.append( 'VAL' ) # add the name for the new column
    olddescr = oldarray.dtype.descr # get the old type descriptor
    formats = [ olddescr[0][1] ] # initialize formats list, enter first 
format
    arrays = [ oldarray[ olddescr[0][0] ] ] # initialize arrays list, 
enter first array
    for i in range( 1 , len(olddescr) ) : # loop over remaining columns
        formats.append( olddescr[i][1] ) # add format of column
        arrays.append( oldarray[ olddescr[i][0] ] ) # add array of column
    formats.append( '<f4' ) # add format of new column
    arrays.append( array( [3.1,3.5,8.1] ) ) # add array of new column
    newarray = fromarrays( arrays , names = names , formats = formats ) 
# make new record array
but that is very ugly programming.
Any Ideas?

Thank you - MGB




More information about the SciPy-user mailing list