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

Christopher Barker Chris.Barker@noaa....
Wed Sep 5 12:24:27 CDT 2007



Günter Dannoritzer wrote:
> 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'

Object arrays are tricky, 'cause it's hard for numpy to know how you 
want to unpack arbitrary objects.

The solution is to make an empty object array first, then populate it. 
For example:

 >>> import numpy as N
 >>> MyData = [[1,2,3],
...           [4,5,6],
...           [7,8,9]]


This is a list or lists, so numpy.array would unpack it into a 2-d array:
 >>> N.array(MyData)
array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
However, let's say what I want is a 1-d object array. I create the 
object array empty:

 >>> OA = N.empty((3,), dtype=N.object)
 >>> OA
array([None, None, None], dtype=object)

Then populate it:

 >>> OA[:] = MyData
 >>> OA
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=object)


Does that help?

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov



More information about the Numpy-discussion mailing list