[Numpy-discussion] Creating array containing empty lists
Pauli Virtanen
pav@iki...
Wed Mar 25 06:29:14 CDT 2009
Wed, 25 Mar 2009 12:04:43 +0100, Jesper Larsen wrote:
> I have a problem with array broadcasting for object arrays and list. I
> would like to create a numpy array containing empty lists (initially - I
> will append to them later):
[clip]
> Is it possible to broadcast a list to all elements of a numpy array? Or
> will I have to loop through it and set the individual elements?
You can use the `fill` method, which will broadcast correctly:
>>> import numpy as np
>>> a = np.empty((5,), dtype=np.object_)
>>> a.fill([])
>>> a
array([[], [], [], [], []], dtype=object)
But note that it's now the *same* list in a[0] and a[1]:
>>> a[0].append('foo')
>>> a
array([['foo'], ['foo'], ['foo'], ['foo'], ['foo']], dtype=object)
You can avoid the loop by vectorizing the list constructor:
>>> a = np.empty((5,), dtype=np.object_)
>>> a.fill([])
>>> a = np.frompyfunc(list,1,1)(a)
>>> a
array([[], [], [], [], []], dtype=object)
>>> a[0].append('foo')
>>> a
array([['foo'], [], [], [], []], dtype=object)
Possibly not any faster or cleaner than the for loop.
--
Pauli Virtanen
More information about the Numpy-discussion
mailing list