2009-07-29 19 views
20

Qual è il modo più pulito per aggiungere un campo a una matrice numpy strutturata? Può essere fatto in modo distruttivo oppure è necessario creare un nuovo array e copiare i campi esistenti? Il contenuto di ogni campo è memorizzato in modo contiguo nella memoria in modo che tale copia possa essere eseguita in modo efficiente?Aggiunta di un campo a una matrice numpy strutturata

risposta

19

Se si utilizza numpy 1.3, sono disponibili anche numpy.lib.recfunctions.append_fields().

Per molte installazioni, è necessario il numero import numpy.lib.recfunctions per accedere a questo. import numpy non consente di vedere numpy.lib.recfunctions

6
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 
+1

Può essere modificato per evitare la duplicazione della memoria? (vedi [questa domanda] (http://stackoverflow.com/q/39965994/974555)) – gerrit

Problemi correlati