What is the numpy.fromiter() function in Python?
Overview
The fromiter() function in Python simply creates a new 1D (one-dimensional) array from an iterable object passed to the object.
Syntax
numpy.fromiter(iter, dtype)
Parameter value
The fromiter() function takes the following parameter values:
iter: This is the iterable object representing the data for the array.dtype: This is the data type of the desired array.
Return value
The fromiter() function returns an output 1D array.
Code example
import numpy as np# Creating an iterable objectmyiterable = (i * i for i in range(3))# Implementing the numpy.fromiter() functionmyarray = np.fromiter(myiterable, float)print(myarray)
Code explanation
- Line 1: We import the
numpymodule. - Line 4: We create an iterable array called
myiterable. - Line 7: We implement the
fromiter()function on the iterable arraymyiterableand assign the output to amyarrayvariable. - Line 9: We print
myarray, the new1Darray.