[Numpy-discussion] Rename record array fields

Robert Kern robert.kern at gmail.com
Wed Feb 20 16:59:13 EST 2008


On Wed, Feb 20, 2008 at 3:10 PM, Sameer DCosta <sameerslists at gmail.com> wrote:
> Is there a way to rename record array fields without making a copy of
>  the whole record array?

Make a new dtype object with the new names. Use the .view() method on
arrays to get a view of the array with the new dtype.


In [1]: from numpy import *

In [2]: olddt = dtype([('foo', int), ('bar', float)])

In [3]: a = zeros(10, olddt)

In [4]: a
Out[4]:
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), (0, 0.0)],
      dtype=[('foo', '<i4'), ('bar', '<f8')])

In [5]: newdt = dtype([('notfoo', int), ('notbar', float)])

In [6]: b = a.view(newdt)

In [7]: b
Out[7]:
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), (0, 0.0)],
      dtype=[('notfoo', '<i4'), ('notbar', '<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