The numpy.fromiter()
function is used to create an ndarray by using a python iterable object. This method mainly returns a one-dimensional ndarray object.
Syntax of numpy.fromiter()
:
Below we have the required syntax to use this function:
numpy.fromiter(iterable, dtype, count)
Parameters:
Let us discuss the parameters of the above function:
- iterable
This parameter is used to represents an iterable object. - dtype
This parameter is used to represent the data type of the resultant array items. - count:
This parameter is used to represent the number of items to read from the buffer in the array.
Note: It is important to specify a count
parameter in order to improve performance of this function. Because the count
parameter allows the fromiter()
function to pre-allocate the output array rather than resizing it on demand.
Returned Value:
This function will return the array created using the iterable object.
Let us now discuss some examples using fromiter()
function.
Basic Example:
Below we have the code snippet of the example using this function:
import numpy as np
a = [0,2,4,9,10,8]
it = iter(a)
x = np.fromiter(it, dtype = float)
print("The output array is :")
print(x)
print("The type of output array is:")
print(type(x))
Output:
The output array is :
[ 0. 2. 4. 9. 10. 8.]
The type of output array is:
<class 'numpy.ndarray'>