سؤال

ما هو أنظف وسيلة لإضافة حقل إلى مجموعة نمباي منظم؟ يمكن أن يتم ذلك المدمر، أم أنها ضرورية لإنشاء مجموعة جديدة ونسخ على الحقول الحالية؟ هي محتويات كل حقل المخزنة متاخم في الذاكرة بحيث يمكن أن يتم ذلك النسخ كفاءة؟

هل كانت مفيدة؟

المحلول

إذا كنت تستخدم نمباي 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top