Open In App

numpy.fromfunction() function – Python

Last Updated : 29 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

numpy.fromfunction() function construct an array by executing a function over each coordinate and the resulting array, therefore, has a value fn(x, y, z) at coordinate (x, y, z).

Syntax : numpy.fromfunction(function, shape,  dtype)

Parameters :

function : [callable] The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis.

shape : [(N, ) tuple of ints] Shape of the output array, which also determines the shape of the coordinate arrays passed to function.

dtype : [data-type, optional] Data-type of the coordinate arrays passed to function.

Return : The output array.

Code #1 :

Python3




# Python program explaining
# numpy.fromfunction() function
    
# importing numpy as geek
import numpy as geek
    
gfg = geek.fromfunction(lambda i, j: i * j, (4, 4), dtype = float)
    
print(gfg)


Output :

[[0. 0. 0. 0.]

[0. 1. 2. 3.]

[0. 2. 4. 6.]

[0. 3. 6. 9.]]

Code #2 :

Python3




# Python program explaining
# numpy.fromfunction() function
    
# importing numpy as geek
import numpy as geek
    
gfg = geek.fromfunction(lambda i, j: i == j, (3, 3), dtype = int)
    
print(gfg)


Output :

[[ True False False]

[False True False]

[False False True]]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads