numpy.fromiter() function – Python (original) (raw)

Last Updated : 01 Sep, 2023

NumPy’s fromiter() function is a handy tool for creating a NumPy array from an iterable object. This iterable can be any Python object that provides elements one at a time. The function is especially useful when you need to convert data from a custom data source, like a file or generator, into a NumPy array for further analysis.

**Syntax : numpy.fromiter(iterable, dtype, count = -1)

**Parameters :

iterable : The iterable object providing data for the array.

dtype : [data-type] Data-type of the returned array.

count : [int, optional] Number of items to read.

**Returns : [ndarray] The output array.

Numpy.fromiter() function creates a Numpy array from an iterable object. where each element is converted and stored in the array. Here is an example of to use ‘**numpy.fromiter()’:

Python3

import numpy as np

my_iterable = [ 1 , 2 , 3 , 4 , 5 , 6 ]

my_array = np.fromiter(my_iterable,dtype = int )

print (my_array)

**Output:

[1,2,3,4,5,6]

**Example 1:

Using the numpy.fromiter() function to create a NumPy array from an iterable generated by a generator expression.

Python3

import numpy as geek

iterable = (x * x * x for x in range ( 4 ))

gfg = geek.fromiter(iterable, int )

print (gfg)

**Output :

[ 0  1  8 27]

**Example 2:

The NumPy array gfg containing the elements generated by the generator expression. In this case, it’s the squares of the numbers from 0 to 5.

Python3

import numpy as geek

iterable = (x * x for x in range ( 6 ))

gfg = geek.fromiter(iterable, float )

print (gfg)

**Output :

[ 0.  1.  4.  9. 16. 25.]

To create a Numpy array from Unicode charcters using ‘**numpy.froiter()’, you can pass an iterable of Unicode strings as input.Each Unicode string can be represented using its corresponding code point.

Python3

import numpy as np

unicode = [ 71 , 101 , 101 , 107 ]

array = np.fromiter( unicode ,dtype = 'U' )

print (array)

**Output:

['G' 'e' 'e' 'k']

In Numpy the ‘U2’ data type reprsents Unicode strings with a fixed length of 2 characters.The ‘U’ indicates that the data type in Unicode, and the number ‘2’ specifies the length of each string.

Here’s an example of to use ‘**U2′ in numpy:

Python3

import numpy as np

a = "python"

b = np.fromiter(a, dtype = 'U2' )

print (b)

**Output:

['p' 'y' 't' 'h' 'o' 'n']