[Numpy-discussion] Use my own data type with NumPy

Robert Kern robert.kern@gmail....
Wed Sep 5 12:18:57 CDT 2007

Günter Dannoritzer wrote:
> Hi,
> 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 [1]: from numpy import *

In [2]: a = empty((3,), dtype=object)

In [3]: a
Out[3]: array([None, None, None], dtype=object)

In [4]: a[:] = [[1], [2], [3]]

In [5]: a
Out[5]: array([[1], [2], [3]], dtype=object)

In [6]: a.shape
Out[6]: (3,)

Robert Kern

"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 mailing list