numpy.fromiter() - ( Creating Arrays with NumPy )
Heading h2
Syntax
import numpy as np
numpy.fromiter(iterable, dtype, count=-1)
Example
import numpy as np
iterable = (x*x for x in range(5))
arr = np.fromiter(iterable, dtype=int)
print(arr)
Output
[ 0 1 4 9 16]
Explanation
NumPy fromiter()
function creates a new one-dimensional array from an iterable object. Iterable may be a list, dict, or any other iterable object. With this function, we can create ndarray directly from an iterable object (e.g., an iterator), separating computer memory allocation from the iteration.
In the above example, we have created a generator expression to generate the iterable object. We have passed this iterable object and the dtype as the parameters of the numpy.fromiter()
function. It returns an ndarray object with dtype equal to 'int'.
Use
NumPy fromiter()
function is used to create an array from an iterable object. We can directly pass generator objects to this function, which can be used to generate a very large sequence of data with minimal memory usage. This function can also be used to create custom generator functions to create arrays with specific data.
Important Points
- NumPy
fromiter()
function is used to create an array from an iterable - This function separates computer memory allocation from the iteration
- We can directly pass a generator object to this function
- This function can be used to create custom generator functions to create arrays with specific data
Summary
In conclusion, NumPy fromiter()
is a very useful function that can create an array from an iterable such as a generator object. This function separates computer memory allocation from the iteration and can be used to create large sequences of data with minimal memory usage. It is a very useful tool for working with custom generator functions to create arrays with specific data formats.