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

Robert Kern robert.kern@gmail....
Mon Oct 13 19:41:24 CDT 2008


On Mon, Oct 13, 2008 at 19:22, Marc Berthoud <mgb11@cornell.edu> wrote:
> 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?

This is somewhat more straightforward:

http://projects.scipy.org/pipermail/numpy-discussion/2007-September/029357.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the SciPy-user mailing list