[Numpy-discussion] construction of object arrays
Keith Goodman
kwgoodman@gmail....
Wed Jun 30 13:19:59 CDT 2010
On Wed, Jun 30, 2010 at 10:56 AM, Neal Becker <ndbecker2@gmail.com> wrote:
> What are ways to construct object arrays? I want an array of objects, each
> element default constructed of a particular object type.
>
> Say my object is class A. I want a multi-dimensional array, each element
> constructed as A().
>
> Right now, I use np.empty ((a,b,c...), dtype=object)
>
> and then iterate over each dimension, assigning elements:
>
> array[a,b,c...] = A()
>
> Any better suggestions?
Instead of iterating, you could use fill:
>> class A(object):
....: def __init__(self, i):
....: self.i = i
....: def __repr__(self):
....: return 'A(' + str(self.i) + ")"
....:
>> x = np.empty((2,3), dtype=object)
>> x.fill(A(0))
>> x
array([[A(0), A(0), A(0)],
[A(0), A(0), A(0)]], dtype=object)
But then each element is a view of the same instance of A:
>> x[0,0].i = 9
>> x
array([[A(9), A(9), A(9)],
[A(9), A(9), A(9)]], dtype=object)
Hmm...this should be pretty fast:
>> shape = (2,3)
>> x = [A(0) for i in range(np.prod(shape))]
>> x = np.asarray(x)
>> x = x.reshape(shape)
>> x
array([[A(0), A(0), A(0)],
[A(0), A(0), A(0)]], dtype=object)
Each element is a copy:
>> x[0,0].i = 9
>> x
array([[A(9), A(0), A(0)],
[A(0), A(0), A(0)]], dtype=object)
More information about the NumPy-Discussion
mailing list