views:

1370

answers:

4

How can I build a numpy array out of a generator object?

Let me illustrate the problem:

>>> import numpy
>>> def gimme():
...   for x in xrange(10):
...     yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In this instance, gimme() is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from numpy.array(list(gimme())), but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?

A: 

How about creating an empty (zeros) array first and then interate through the dataset updating the array? Of course you'll have to know how big your array is going to be.

initial_len = 10
myarray = zeros((initial_len))
idx = 0
for i in gimme():
    myarray[idx] = i
    idx += 1
monkut
+9  A: 

Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute much quicker than regular lists.

Keeping this in mind, it is technically impossible to take a generator object and turn it into an array unless you either:

(a) can predict how many elements it will yield when run:

my_array = numpy.zeros(predict_length())
for i, el in enumerate(gimme()): my_array[i] = el

(b) are willing to store its elements in an intermediate list :

my_array = numpy.array(list(gimme()))

(c) can make two identical generators, run through the first one to find the total length, initialize the array, and then run through the generator again to find each element:

length = sum(1 for el in gimme())
my_array = numpy.zeros(length)
for i, el in enumerate(gimme()): my_array[i] = el

(a) is probably what you're looking for. (b) is space inefficient, and (c) is time inefficient (you have to go through the generator twice).

shsmurfy
Thanks, that makes alot of sense.
saffsd
+7  A: 

One google behind this stackoverflow result, I found that there is a numpy.fromiter(data, dtype, count). If you set count to -1, it will do what is desired. It also seems to require a dtype to be set. In my case, this worked:

numpy.fromiter(something.generate(from_this_input), float, count=-1)

dhill
Interesting, I shall try it the next time I need it.
saffsd
A: 

Somewhat tangential, but if your generator is a list comprehension, you can use numpy.where to more effectively get your result (I discovered this in my own code after seeing this post)

Benjamin Horstman