Pregunta

¿Cuál es la forma más limpia de agregar un campo a una matriz numpy estructurada? ¿Se puede hacer de forma destructiva o es necesario crear una nueva matriz y copiar sobre los campos existentes? ¿Los contenidos de cada campo se almacenan de forma contigua en la memoria para que dicha copia se pueda realizar de manera eficiente?

¿Fue útil?

Solución

Si está usando numpy 1.3, también hay numpy.lib.recfunctions.append_fields ().

Para muchas instalaciones, deberás importar numpy.lib.recfunctions para acceder a este. import numpy no le permitirá a uno ver el numpy.lib.recfunctions

Otros consejos

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top