In this article, we will see how to build a numpy array from the generator.
Using generator functions we can iterate over an infinite sequence of values without storing them in a memory. They are particularly useful when dealing with large datasets.
Let’s see how to build a numpy array from a generator with an example.
Using the fromiter
function from the Numpy, we can build an array from an iterable object. Following is an example:
import numpy as np
def data_generator():
for i in range(10):
yield i
generator = data_generator()
array = np.fromiter(generator, dtype=int, count=10)
print(array)
In the above example, the data_generator()
function yields integers from 0 to 9 and then we created an instance of generator and pass it to np.fromiter()
. This function takes three arguments i.e. iterable object, data type and no of elements to be consumed from the iterator.
After calling np.fromiter()
, we get a NumPy aray which contains the values provided by the generator and then print the array which leads to following output.
<code>[0 1 2 3 4 5 6 7 8 9]