The fromfunction()
function in Python constructs an array by executing a function over each coordinate. The output array has a value fn(x, y, z)
at the (x, y, z)
coordinate.
numpy.fromfunction(function, shape, *, dtype=<class 'float'>)
The fromfunction()
function takes the following parameter values:
function
: This represents the function called with N
parameters. Here, N
represents the rank of the shape
.
shape
: This represents an output array’s shape. This also determines the shape of the coordinate arrays passed to function
.
dtype
: This represents the data type of the coordinate arrays passed to function
. This is optional, and by default, dtype
is a float.
fromfunction()
outputs an array. The result of the call to function is passed back directly. Therefore, the shape of the output array is completely determined by function
.
import numpy as np# implementing the fromfunction() functionmyarray = np.fromfunction(lambda x, y: x + y, (2, 2), dtype=int)print(myarray)
Line 1: We import the numpy
module.
Line 4: We implement the fromfunction()
function on a lambda function that has a 2D
array with an integer data type. We assigned the output to a variable, myarray
.
Line 6: We print myarray
.