numpy.fromfunction#
- numpy.fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)[source]#
Construct an array by executing a function over each coordinate.
The function is called once with one coordinate array for each dimension of
shapeinstead of once per coordinate.For functions that operate elementwise on array arguments, the resulting array has a value
fn(x, y, z)at coordinate(x, y, z).- Parameters:
- functioncallable
The function is called once with N coordinate arrays as parameters, where N is the length of
shape. Each array represents the coordinates along a specific axis. For example, ifshapewere(2, 2), then the parameters would bearray([[0, 0], [1, 1]])andarray([[0, 1], [0, 1]])- shape(N,) tuple of ints
Shape of the coordinate arrays passed to function. The shape of the output is determined by the value returned by function and may be different from
shape- dtypedata-type, optional
Data-type of the coordinate arrays passed to function. By default,
dtypeis float.- likearray_like, optional
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as
likesupports 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:
- fromfunctionany
The result of the call to function is passed back directly. Therefore the shape of
fromfunctionis completely determined by function. If function returns a scalar value, the shape offromfunctionwould not match theshapeparameter.
Notes
Keywords other than
dtypeand like are passed to function.Warning
shapedetermines the shape of the coordinate arrays passed to function. It does not enforce that the function returns a result with that shape. If function returns a scalar, the result is a scalar rather than an array with the givenshape.Examples
>>> import numpy as np >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=np.float64) array([[0., 0.], [1., 1.]])
>>> np.fromfunction(lambda i, j: j, (2, 2), dtype=np.float64) array([[0., 1.], [0., 1.]])
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=np.int_) array([[ True, False, False], [False, True, False], [False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=np.int_) array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])