代码之家  ›  专栏  ›  技术社区  ›  Vebjorn Ljosa

向结构化numpy数组添加字段

  •  21
  • Vebjorn Ljosa  · 技术社区  · 15 年前

    将字段添加到结构化numpy数组中最干净的方法是什么?它可以被破坏性地完成,还是需要创建一个新的数组并在现有字段上进行复制?每个字段的内容是否连续存储在内存中,以便有效地进行复制?

    2 回复  |  直到 9 年前
        1
  •  19
  •   Roland    11 年前

    如果您使用的是numpy 1.3,那么还有numpy.lib.recfunctions.append_fields()。

    对于许多安装,您需要 import numpy.lib.recfunctions 访问此。 import numpy 不会让人看到 numpy.lib.recfunctions

        2
  •  6
  •   strpeter davidsheldon    9 年前
    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