What is fromfunction() from numpy in Python?
Overview
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.
Syntax
numpy.fromfunction(function, shape, *, dtype=<class 'float'>)
The fromfunction() function takes the following parameter values:
-
function: This represents the function called withNparameters. Here,Nrepresents the rank of theshape. -
shape: This represents an output array’s shape. This also determines the shape of the coordinate arrays passed tofunction. -
dtype: This represents the data type of the coordinate arrays passed tofunction. This is optional, and by default,dtypeis a float.
Return value
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.
Code example
import numpy as np# implementing the fromfunction() functionmyarray = np.fromfunction(lambda x, y: x + y, (2, 2), dtype=int)print(myarray)
Code explanation
-
Line 1: We import the
numpymodule. -
Line 4: We implement the
fromfunction()function on a lambda function that has a2Darray with an integer data type. We assigned the output to a variable,myarray. -
Line 6: We print
myarray.