NumPy fromiter() Function:
Numpy fromiter: The fromiter() function of the NumPy module creates a new 1-dimensional array from an iterable object.
Syntax:
numpy.fromiter(iterable, dtype, count=-1)
Parameters
iterable: This is required. It is an iterable object that provides data for the array.
dtype: This is required. It denotes the data type of the array returned.
count: This is optional. It represents the number of items to read from an iterable. The default value is -1, which means that all the data is read.
Return Value:
An array created from an iterable object is returned
- Python Pandas DataFrame items() Function
- Python NumPy loadtxt() Function
- How to Use NumPy to Create a Numeric Sequence in Python?
NumPy fromiter() Function in Python
Example1
Approach:
- Import numpy module using the import keyword
- Get the square of values from 0 to n(random number) using tuple compherension
- Store it in a variable.
- Pass the above iterable, datatype as float as arguments fromiter() function of
numpy module to create a numpy array from the given iterable - Store it in another variable.
- Print the above-obtained result array.
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Get the square of values from 0 to n(random number) using tuple compherension # Store it in a variable. gvn_itrable = (p*p for p in range(10)) # Pass the above iterable, datatype as float as arguments to the fromiter() function of # numpy module to create a numpy array from the given iterable # Store it in another variable. rslt_arry = np.fromiter(gvn_itrable, dtype=float) # Print the above obtained result array print(rslt_arry)
Output:
[ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81.]
Example2
Approach:
- Import numpy module using the import keyword
- Get the square of values from 0 to n(random number) using tuple compherension
- Store it in a variable.
- Pass the above iterable, datatype as float, some random count as arguments to the fromiter() function of numpy module to create a numpy array from the given iterable of count number of values.
- Store it in another variable.
- Here it prints the first 6 elements.
- Print the above-obtained result array.
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Get the square of values from 0 to n(random number) using tuple compherension # Store it in a variable. gvn_itrable = (p*p for p in range(10)) # Pass the above iterable, datatype as float, some random count as arguments to the # fromiter() function of numpy module to create a numpy array from the given iterable # of count number of values. # Store it in another variable. # Here it prints the first 6 elements. rslt_arry = np.fromiter(gvn_itrable, dtype=float, count=6) # Print the above obtained result array print(rslt_arry)
Output:
[ 0. 1. 4. 9. 16. 25.]