How Do I Build A Numpy Array From A Generator?
Last Updated :
28 Apr, 2025
NumPy is a powerful library in Python for numerical operations, and it provides an efficient array object, numpy.ndarray
, for working with large datasets. Often, data is generated using generators, and it becomes necessary to convert this data into NumPy arrays for further analysis. In this article, we'll explore some different methods to build a NumPy array from a generator.
How Do I Build A Numpy Array From A Generator?
Below, are the ways to Build A Numpy Array From A Generator in Python.
Numpy Array From A Generator Using numpy.fromiter()
In this example, the below code defines a generator function generator()
that yields numbers from 1 to 10. It then uses NumPy's fromiter
function to create an array from the generator, storing it in the variable arr
. Finally, it prints the array and its data type.
Python3
#importing numpy library
import numpy as np
#generator function
def generator():
n = 10
for i in range(1,n+1):
yield i
print(type(generator()))
if __name__ == "__main__":
#calling the function and storing in our arrya
arr = np.fromiter(generator(), dtype=int,count=-1)
#Displaying the array
print("Array : {}".format(arr))
print(type(arr))
Output :
<class 'generator'>
Array : [ 1 2 3 4 5 6 7 8 9 10]
<class 'numpy.ndarray'>
Numpy Array From A Generator Using numpy.array()
In this example , below code defines a generator function generator()
that yields numbers from 1 to 10. It then converts the generator output to a list and creates a NumPy array from that list using np.array()
, storing it in the variable arr
. Finally, it prints the array and its data type.
Python3
# importing numpy library
import numpy as np
# generator function
def generator():
n = 10
for i in range(1, n+1):
yield i
print(type(generator()))
if __name__ == "__main__":
# calling the function and storing in our arrya
arr = np.array(list(generator()), dtype=int)
# Displaying the array
print("Array : {}".format(arr))
print(type(arr))
Output :
<class 'generator'>
Array : [ 1 2 3 4 5 6 7 8 9 10]
<class 'numpy.ndarray'>
Numpy Array From A Generator Using numpy.concatenate()
In this example, below code defines a generator function generator()
that yields numbers from 1 to 10. It then converts the generator output to a list (gen_list
) and uses NumPy's np.concatenate()
to concatenate the list and create an array (arr
). Finally, it prints the array and its data type.
Python3
# importing numpy library
import numpy as np
# generator function
def generator():
n = 10
for i in range(1, n + 1):
yield i
print(type(generator()))
if __name__ == "__main__":
# calling the function and converting the
#generator to a list
gen_list = list(generator())
arr = np.concatenate([gen_list], dtype=int)
# Displaying the array
print("Array: {}".format(arr))
print("Type of Array:", type(arr))
Output :
<class 'generator'>
Array: [ 1 2 3 4 5 6 7 8 9 10]
Type of Array: <class 'numpy.ndarray'>
Conclusion
In conclusion, building a NumPy array from a generator provides a memory-efficient way to handle large datasets by generating data on-the-fly. Utilizing the numpy.fromiter
function or directly converting a generator expression to an array with numpy.array
allows for seamless integration of generator-based data into NumPy workflows. This approach not only conserves resources but also enhances the overall efficiency and performance of numerical operations in Python.
Similar Reads
How to convert a dictionary into a NumPy array? It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a
3 min read
How to access a NumPy array by column Accessing a NumPy-based array by a specific Column index can be achieved by indexing. NumPy follows standard 0-based indexing in Python. Â Example:Given array: 1 13 6 9 4 7 19 16 2 Input: print(NumPy_array_name[ :,2]) Output: [6 7 2] Explanation: printing 3rd columnAccess ith column of a 2D Numpy Arr
3 min read
How to build an array of all combinations of two NumPy arrays? Our task is to build an array containing all possible combinations of elements from two NumPy arrays. To achieve this, we can utilize the np.meshgrid() function, which creates coordinate grids from the arrays. By reshaping these grids, we can generate a 2D array that holds every combination of value
3 min read
Convert a NumPy array to an image Converting a NumPy array to an image is a simple way to turn numbers into pictures. A NumPy array holds pixel values, which are just numbers that represent colors. Images, like PNG or JPEG, store these pixel values in a format we can see. In this process, the NumPy array turns into an image, with ea
3 min read
Convert a NumPy array into a CSV file After completing your data science or data analysis project, you might want to save the data or share it with others. Exporting a NumPy array to a CSV file is the most common way of sharing data. CSV file format is the easiest and most useful format for storing data and is convenient to share with o
3 min read
How to convert NumPy array to list ? This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding. Convert NumPy Array to List There are various ways to convert NumPy Array to List here we are discussing some generally us
4 min read
Insert a new axis within a NumPy array This post deals with the ways to increase the dimension of an array in NumPy. NumPy provides us with two different built-in functions to increase the dimension of an array i.e., 1D array will become 2D array2D array will become 3D array3D array will become 4D array4D array will become 5D arrayAdd a
4 min read
How to Convert NumPy Matrix to Array In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read
How to convert a list and tuple into NumPy arrays? In this article, let's discuss how to convert a list and tuple into arrays using NumPy. NumPy provides various methods to do the same using Python. Example: Input: [3, 4, 5, 6]Output: [3 4 5 6]Explanation: Python list is converted into NumPy ArrayInput: ([8, 4, 6], [1, 2, 3])Output: [[8 4 6] [1 2 3]
2 min read
How to Convert images to NumPy array? Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. Â In this article we will see How to Convert images to NumPy array? Mod
6 min read