numpy.fromiter#
- numpy.fromiter(iter,dtype,count=-1,*,like=None)#
Create a new 1-dimensional array from an iterable object.
- Parameters:
- iteriterable object
An iterable object providing data for the array.
- dtypedata-type
The data-type of the returned array.
Changed in version 1.23:Object and subarray dtypes are now supported (note that the finalresult is not 1-D for a subarray dtype).
- countint, optional
The number of items to read fromiterable. The default is -1,which means all data is read.
- likearray_like, optional
Reference object to allow the creation of arrays which are notNumPy arrays. If an array-like passed in as
likesupportsthe__array_function__protocol, the result will be definedby it. In this case, it ensures the creation of an array objectcompatible with that passed in via this argument.New in version 1.20.0.
- Returns:
- outndarray
The output array.
Notes
Specifycount to improve performance. It allows
fromitertopre-allocate the output array, instead of resizing it on demand.Examples
>>>importnumpyasnp>>>iterable=(x*xforxinrange(5))>>>np.fromiter(iterable,float)array([ 0., 1., 4., 9., 16.])
A carefully constructed subarray dtype will lead to higher dimensionalresults:
>>>iterable=((x+1,x+2)forxinrange(5))>>>np.fromiter(iterable,dtype=np.dtype((int,2)))array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])