adding an attribute to an nd-array

Albert Strasheim fullung at gmail.com
Fri Oct 27 17:37:19 CDT 2006


Hello all

> -----Original Message-----
> From: numpy-discussion-bounces at lists.sourceforge.net [mailto:numpy-
> discussion-bounces at lists.sourceforge.net] On Behalf Of Travis Oliphant
> Sent: Thursday, October 19, 2006 5:45 PM
> To: Discussion of Numerical Python
> Subject: Re: [Numpy-discussion] adding an attribute to an nd-array
> 
> Stefan van der Walt wrote:
> 
> >On Wed, Oct 18, 2006 at 09:17:49PM -0400, Pierre GM wrote:
> >>On Wednesday 18 October 2006 20:29, Stefan van der Walt wrote:
> >>>A quick question on extending numpy arrays: is it possible to easily
> >>>add an attribute to an ndarray?
> >>It might be easier to create a subclass: pleasehave a look here:
> >>http://projects.scipy.org/scipy/numpy/attachment/wiki/MaskedArray/test_s
> ubclasses.py
> >>That's a tiny example of subclassing ndarrays, with some extra
> attributes.
> >>(BTW, I'm not sure that's the most obvious place where to look: if it
> turns
> >>out to be useful, I'll put it on the scipy wiki)
> >
> >Thanks very much, Pierre.
> >
> >If I understand correctly, the following should work:
> >
> >import numpy as N
> >
> >class InfoArray(N.ndarray):
> >    def __new__(info_arr_cls,arr,info={}):
> >        info_arr_cls.info = info
> >        return N.array(arr).view(info_arr_cls)
> >
> >When does __array_finalize__ get called, and is it always necessary to
> >specify it?
> 
> Actually something as simple as
> 
> class InfoArray(N.ndarray):
>          pass
> 
> will allow you to add attributes to InfoArray.

I would like to create an "info" array like this to attach some metadata,
mostly sampling frequency, to some of my arrays.

The first problem I'm running into is that this new InfoArray type needs
something like the array function so that I can create it from an existing
"normal" array. It would also be useful if metadata could survive through
type conversions like this:

y = array(x, 'f4')

One frequently wants to do this where you start with a 8-bit or 16-bit
samples of a speech signal and you then want to convert to a floating point
type for further processing.

I browsed through the NumPy book and looked at the __new__ and
__array_finalize__ stuff in Pierre GM's new MaskedArray, but I'm still
thoroughly confused about how to create a simple array+metadata subclass
that Just Works(TM).

Does anybody have some code that they would be willing to share?

Thanks.

Regards,

Albert


-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642




More information about the Numpy-discussion mailing list