質問

構造化されたnumpy配列にフィールドを追加する最もクリーンな方法は何ですか?破壊的に実行できますか、または新しい配列を作成して既存のフィールドをコピーする必要がありますか?このようなコピーを効率的に実行できるように、各フィールドの内容はメモリに連続して格納されていますか?

役に立ちましたか?

解決

numpy 1.3を使用している場合、numpy.lib.recfunctions.append_fields()もあります。

多くのインストールでは、 numpy.lib.recfunctionsをインポートしてこれにアクセスする必要があります。 import numpy は、 numpy.lib.recfunctions

の表示を許可しません。

他のヒント

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top