This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Attachment 'obarray.py'

Download

   1 import numpy as np
   2 def make_obarray(klass, dtype):
   3     class Obarray(np.ndarray):
   4         def __new__(cls, obj):
   5             A = np.array(obj,dtype=np.object)
   6             N = np.empty(shape=A.shape, dtype=dtype)
   7             for idx in np.ndindex(A.shape):
   8                 for name, type in dtype:
   9                     N[name][idx] = type(getattr(A[idx],name))
  10             return N.view(cls)
  11         def __getitem__(self, idx):
  12             V = np.ndarray.__getitem__(self,idx)
  13             if np.isscalar(V):
  14                 kwargs = {}
  15                 for i, (name, type) in enumerate(dtype):
  16                      kwargs[name] = V[i]
  17                 return klass(**kwargs)
  18             else:
  19                 return V
  20         def __setitem__(self, idx, value):
  21             if isinstance(value, klass):
  22                 value = tuple(getattr(value, name) for name, type in dtype)
  23             # FIXME: treat lists of lists and whatnot as arrays
  24             return np.ndarray.__setitem__(self, idx, value)
  25     return Obarray

New Attachment

File to upload
Rename to
Overwrite existing attachment of same name

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.