[Numpy-discussion] Use my own data type with NumPy
Wed Sep 5 12:18:57 CDT 2007
Günter Dannoritzer wrote:
> I am trying to use my own data type with NumPy, but get some funny
> result when creating a NumPy array with it.
> My data type is indexable and sliceable and what happens now is when I
> create an array, NumPy is adding the instance as a list of the indexed
> values. How can I force NumPy to handle my data type as an 'Object' and
> use the value of __repr__ to display in the array?
> Maybe I am handling that too simple, as I had another data type before,
> -- not indexable though --, that just works fine with NumPy. Do I have
> to worry about a dtype object with my new data type or how can I use my
> new data type with NumPy?
I presume that by "new data type" you mean some Python class that you've made,
not some C data type.
Creating an object array can be a bit tricky. array() has to make some guesses
as to which objects are containers and which are elements. Sometimes, it guesses
wrong (at least measured against what the user actually desired). The most
robust way to construct an object array is to create an empty() object array of
the shape you want, and then assign the contents.
In : from numpy import *
In : a = empty((3,), dtype=object)
In : a
Out: array([None, None, None], dtype=object)
In : a[:] = [, , ]
In : a
Out: array([, , ], dtype=object)
In : a.shape
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion