[Numpy-discussion] Expected behavior of numpy object arrays. Is this a bug?

Rudolph van der Merwe rudolphv at gmail.com
Thu May 17 15:03:59 EDT 2007


Robert,

Thanks for the suggestion on creating an empty object array first (of
the needed shape) and then assigning the entries. It works like a
charm.

Rudolph


On 5/17/07, Robert Kern <robert.kern at gmail.com> wrote:
> Rudolph van der Merwe wrote:
> > Can someone please confirm if the following is the expected behavior
> > of numpy ndarrays of dtype=object, i.e. object arrays. I suspect it
> > might be a bug.
>
> It's expected. The array() function has to make some guesses as to what you
> meant when you pass it a sequence of sequences and are trying to make an object
> array. It tries to go as deep as it can. When you give it a list of len-2
> sequences, it thinks you want a (2, 2) array. When you give it a list of a len-2
> sequence an a len-3 sequence, the only thing it can do is make a (2,) array of
> the two objects.
>
> The best way to build the array you want is to make the object array first, and
> assign the contents:
>
>
> In [1]: from numpy import *
>
> In [2]: a = array([1, 2])
>
> In [3]: b = array([5, 6, 7])
>
> In [4]: c = array([3, 4])
>
> In [5]: oa1 = empty([2], dtype=object)
>
> In [6]: oa2 = empty([2], dtype=object)
>
> In [7]: oa1[:] = [a, b]
>
> In [8]: oa2[:] = [a, c]
>
> In [9]: oa1
> Out[9]: array([[1 2], [5 6 7]], dtype=object)
>
> In [10]: oa2
> Out[10]: array([[1 2], [3 4]], dtype=object)
>
> In [11]: oa1[0].dtype
> Out[11]: dtype('int32')
>
> In [12]: oa2[0].dtype
> Out[12]: dtype('int32')
>
> --
> 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
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>


-- 
Rudolph van der Merwe



More information about the NumPy-Discussion mailing list