NumPy Fromiter Function

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will cover the NumPy fromiter() function which is used to create an ndarray by using a Python iterable object. We will explain the syntax, parameters, and return value of this function along with a code example.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import the NumPy Library

We begin by importing the NumPy library using the following code:

import numpy as np

Here, np is an alias for the NumPy library which we will use throughout the code.

Create Python Iterable Object

In this step, we create a Python iterable object which will be used to create the ndarray later on. We can create any iterable object including lists, tuples, and generators. For this example, we create a list of integers:

a = [0, 2, 4, 9, 10, 8]

Create the ndarray using the fromiter() Function

We can now create an ndarray using the fromiter() function as follows:

it = iter(a)
x = np.fromiter(it, dtype=float)

Here, we first pass the iterable object a to the iter() function to create an iterator object it. This iterator object is then passed to the fromiter() function along with the data type of the array we wish to create which in this case is float.

Display the Output

We can display the output array and its data type using the following code:

print("The output array is :")
print(x)
print("The type of output array is:")
print(type(x))

Here, we first print the output array followed by its data type.

Specify the Number of Items to Read

It is important to note that we can improve the performance of the fromiter() function by specifying the count parameter. This parameter allows the fromiter() function to pre-allocate the output array rather than resizing it on demand. The count parameter represents the number of items to read from the buffer in the array. We can specify the count parameter as follows:

x = np.fromiter(a, dtype=float, count=len(a))

Here, we pass the iterable object a along with the data type float and the count of the number of items which is equal to len(a).

Summary

In this lab, we covered the NumPy fromiter() function which is used to create an ndarray by using a Python iterable object. We explained the syntax, parameters, and return value of this function. We also provided a code example demonstrating how to use this function to create an array. By following the steps outlined in this lab, you should now have a good understanding of how to use the fromiter() function in NumPy.

Other Python Tutorials you may like