向结构化numpy数组添加字段

22 投票
2 回答
9453 浏览
提问于 2025-04-15 13:15

在一个有结构的numpy数组中,添加一个字段最简单的方法是什么?这个操作可以直接在原数组上进行吗,还是必须创建一个新数组并把原来的字段复制过去?每个字段的内容在内存中是连续存储的吗,这样复制的时候能更高效吗?

2 个回答

8

在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够好,或者是我们对某些概念理解得不够透彻。比如,有人可能在使用某个库或者框架的时候,遇到了错误或者不明白怎么用。这种时候,查看其他人的提问和回答就很有帮助。

在StackOverflow上,很多人会分享他们遇到的问题和解决方案。通过这些讨论,我们可以学习到很多实用的技巧和知识,帮助我们更好地理解编程的世界。

总之,遇到问题时,不要害怕去寻求帮助,看看别人是怎么解决类似的问题的,这样可以让我们进步得更快。

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
20

如果你在使用numpy 1.3版本的话,还有一个叫做numpy.lib.recfunctions.append_fields()的功能。

在很多情况下,你需要先用import numpy.lib.recfunctions来访问这个功能。单单使用import numpy是看不到numpy.lib.recfunctions的。

撰写回答