numpy.fromfunction(function, shape, *, dtype=<class'float'>, like=None, **kwargs)
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value fn(x,y,z) at coordinate (x,y,z).
Parameters:functioncallableThe function is called with N parameters, where N is the rank of
. Each parameter represents the coordinates of the array varying along a specific axis. For example, if
were (2,2), then the parameters would be array([[0,0],[1,1]]) and array([[0,1],[0,1]])
shape(N,) tuple of intsShape of the output array, which also determines the shape of the coordinate arrays passed to function.
dtypedata-type, optionalData-type of the coordinate arrays passed to function. By default,
is float.
likearray_like, optionalReference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
Added in version 1.20.0.
Returns:fromfunctionanyThe result of the call to function is passed back directly. Therefore the shape of
is completely determined by function. If function returns a scalar value, the shape of
would not match the
parameter.
Notes
Keywords other than
and like are passed to function.
Examples
>>> importnumpyasnp>>> np.fromfunction(lambdai,j:i,(2,2),dtype=np.float64)array([[0., 0.], [1., 1.]])>>> np.fromfunction(lambdai,j:j,(2,2),dtype=np.float64)array([[0., 1.], [0., 1.]])>>> np.fromfunction(lambdai,j:i==j,(3,3),dtype=np.int_)array([[ True, False, False], [False, True, False], [False, False, True]])>>> np.fromfunction(lambdai,j:i+j,(3,3),dtype=np.int_)array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])