[Numpy-discussion] adding field to rec array

Robert Kern robert.kern at gmail.com
Wed Sep 26 14:07:49 EDT 2007


John Hunter wrote:
> I have a record array r and I want to add a new field to it.  I have
> been looking at setfield but I am not sure how to use it for this
> purpose.  Eg
> 
> # r is some npy record array
> N = len(r)
> x = npy.zeros(N)
> # add array of floats x to r with dtype name 'jdh' and type '<f8'
> 
> Any suggestions?

Here is the straightforward way:


In [15]: import numpy as np

In [16]: dt = np.dtype([('foo', int), ('bar', float)])

In [17]: r = np.zeros((3,3), dtype=dt)

In [18]: r
Out[18]:
array([[(0, 0.0), (0, 0.0), (0, 0.0)],
       [(0, 0.0), (0, 0.0), (0, 0.0)],
       [(0, 0.0), (0, 0.0), (0, 0.0)]],
      dtype=[('foo', '<i4'), ('bar', '<f8')])

In [19]: def append_field(rec, name, arr, dtype=None):
    arr = np.asarray(arr)
    if dtype is None:
        dtype = arr.dtype
    newdtype = np.dtype(rec.dtype.descr + [(name, dtype)])
    newrec = np.empty(rec.shape, dtype=newdtype)
    for field in rec.dtype.fields:
        newrec[field] = rec[field]
    newrec[name] = arr
    return newrec
   ....:

In [29]: append_field(r, 'jdh', ones((3,3)))
Out[29]:
array([[(0, 0.0, 1.0), (0, 0.0, 1.0), (0, 0.0, 1.0)],
       [(0, 0.0, 1.0), (0, 0.0, 1.0), (0, 0.0, 1.0)],
       [(0, 0.0, 1.0), (0, 0.0, 1.0), (0, 0.0, 1.0)]],
      dtype=[('foo', '<i4'), ('bar', '<f8'), ('jdh', '<f8')])


-- 
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 NumPy-Discussion mailing list