[Numpy-discussion] Re: array of arbitrary objects
Tim Hochberg
tim.hochberg at cox.net
Wed May 10 20:48:04 EDT 2006
Albert Strasheim wrote:
>Hello all
>
>
>
>>-----Original Message-----
>>From: numpy-discussion-admin at lists.sourceforge.net [mailto:numpy-
>>discussion-admin at lists.sourceforge.net] On Behalf Of Robert Kern
>>Sent: 11 May 2006 05:28
>>To: numpy-discussion at lists.sourceforge.net
>>Subject: [Numpy-discussion] Re: array of arbitrary objects
>>
>>Ryan Krauss wrote:
>>
>>
>>>Is it possible with numpy to create arrays of arbitrary objects?
>>>Specifically, I have defined a symbolic string class with operator
>>>overloading for most simple math operations: 'a'*'b' ==> 'a*b'
>>>
>>>Can I create two matrices of these symbolic string objects and
>>>multiply those matrices together?
>>>
>>>(simply doing array([[a,b],[c,d]]) did not work. the symbolic strings
>>>got cast to regular strings)
>>>
>>>
>>Use dtype=object .
>>
>>
>
>How does one go about putting tuples into an object array?
>
>Consider the following example, courtesy of Louis Cordier:
>
>In [1]: import numpy as N
>In [2]: a = [(1,2), (2,3), (3,4)]
>In [3]: len(a)
>Out[3]: 3
>In [5]: N.array(a, 'O')
>Out[5]:
>array([[1, 2],
> [2, 3],
> [3, 4]], dtype=object)
>
>instead of something like this:
>
>array([[(1, 2), (2, 3), (3, 4)]], dtype=object)
>
>
Creating object arrays is always going to be a bit of a pain, however,
the following approach will work here:
>>> import numpy as N
>>> a = [(1,2), (2,3), (3,4)]
>>> b = N.zeros([len(a)], object)
>>> b[:] = a
>>> b
array([(1, 2), (2, 3), (3, 4)], dtype=object)
>>> type(b[0])
<type 'tuple'>
Regards,
-tim
More information about the NumPy-Discussion
mailing list