2009-07-29 98 views
20

將結構化numpy數組中添加字段的最簡單方法是什麼?它可以破壞性地完成,還是需要創建一個新的數組並複製現有的字段?每個字段的內容是否連續存儲在內存中,以便可以高效地完成這種複製?將字段添加到結構化numpy數組中

回答

19

如果您使用numpy 1.3,還有numpy.lib.recfunctions.append_fields()。

對於許多安裝,您需要import numpy.lib.recfunctions才能訪問此操作。 import numpy不會讓人看到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

可以修改這個以避免重複記憶嗎? (請參閱[此問題](http://stackoverflow.com/q/39965994/974555)) – gerrit 2016-10-10 20:21:57