Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a field to a structured numpy array

Tags:

What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently?

like image 989
Vebjorn Ljosa Avatar asked Jul 29 '09 17:07

Vebjorn Ljosa


People also ask

How do I add something to a NumPy array?

You can add a NumPy array element by using the append() method of the NumPy module. The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above. The axis is an optional integer along which define how the array is going to be displayed.

Can you append values to NumPy array?

append() is used to append values to the end of an array. It takes in the following arguments: arr : values are attached to a copy of this array.

What is a structured array in NumPy?

Structured arrays are ndarrays whose datatype is a composition of simpler datatypes organized as a sequence of named fields. For example, >>> x = np. array([('Rex', 9, 81.0), ('Fido', 3, 27.0)], ... dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')]) >>> x array([('Rex', 9, 81.), ('


2 Answers

If you're using numpy 1.3, there's also numpy.lib.recfunctions.append_fields().

For many installations, you'll need to import numpy.lib.recfunctions to access this. import numpy will not allow one to see the numpy.lib.recfunctions

like image 77
DopplerShift Avatar answered Oct 20 '22 01:10

DopplerShift


import numpy  def add_field(a, descr):     """Return a new array that is like "a", but has additional fields.      Arguments:       a     -- a structured numpy array       descr -- a numpy type description of the new fields      The contents of "a" are copied over to the appropriate fields in     the new array, whereas the new fields are uninitialized.  The     arguments are not modified.      >>> sa = numpy.array([(1, 'Foo'), (2, 'Bar')], \                          dtype=[('id', int), ('name', 'S3')])     >>> sa.dtype.descr == numpy.dtype([('id', int), ('name', 'S3')])     True     >>> sb = add_field(sa, [('score', float)])     >>> sb.dtype.descr == numpy.dtype([('id', int), ('name', 'S3'), \                                        ('score', float)])     True     >>> numpy.all(sa['id'] == sb['id'])     True     >>> numpy.all(sa['name'] == sb['name'])     True     """     if a.dtype.fields is None:         raise ValueError, "`A' must be a structured numpy array"     b = numpy.empty(a.shape, dtype=a.dtype.descr + descr)     for name in a.dtype.names:         b[name] = a[name]     return b 
like image 44
Vebjorn Ljosa Avatar answered Oct 20 '22 00:10

Vebjorn Ljosa