문제
구조화 된 Numpy 어레이에 필드를 추가하는 가장 깨끗한 방법은 무엇입니까? 파괴적으로 수행 할 수 있습니까, 아니면 새 배열을 만들고 기존 필드를 통해 복사해야합니까? 각 필드의 내용물이 이러한 복사를 효율적으로 수행 할 수 있도록 메모리에 연속적으로 저장됩니까?
해결책
Numpy 1.3을 사용하는 경우 Numpy.lib.recfunctions.append_fields ()도 있습니다.
많은 설치를 위해서는 필요합니다 import 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
제휴하지 않습니다 StackOverflow