BetterDocs
Home
Docs

Creation | np.fromfunction()

Method:

np.fromfunction(function, shape, *, dtype=np.float64, like=None)

Constructs an array by applying a function to each coordinate.

Returns:

np.ndarray

Parameters:

function: function-

Function to apply to each coordinate.

import numpy as np

# 3x3 array where each entry is i + j (row + column index)
fromfunction_array = np.fromfunction(function=lambda i, j: i + j, shape=(3, 3))
print(fromfunction_array)
'''
Output:
[[0. 1. 2.]
 [1. 2. 3.]
 [2. 3. 4.]]
 '''

shape: dimension-

Dimensions of the new array.

import numpy as np

# 3x2 array where each entry is i + j (row + column index)
fromfunction_array = np.fromfunction(function=lambda i, j: i + j, shape=(3, 2))
print(fromfunction_array)
'''
Output:
[[0. 1.]
 [1. 2.]
 [2. 3.]]
'''

The shape of an np.ndarray is related to it's dimensions.

shape is an array of numbers representing the length of each dimension.

dtype: np.float64, Optional-

The desired data-type for the NumPy array.

import numpy as np

# 1x5 array where each entry is i + j (row + column index)
fromfunction_array = np.fromfunction(function=lambda i, j: i + j, shape=(1, 5), dtype=np.int32)
print(fromfunction_array)
'''
Output:
[[0 1 2 3 4]]
'''

Values: +

By passing the dtype, you are implicitly converting the values to the passed dtype.

like: None, Optional-

The like parameter in np.fromfunction() was introduced to make array creation more flexible, particularly for compatibility with libraries that extend NumPy, like Dask, CuPy, or other libraries that create arrays compatible with np.ndarray but optimized for different backends (e.g., parallel processing or GPU-based arrays).


Logo

BetterDocs

Support

EmailDiscordForms

Documentations

Python

Company

AboutDocs

Policies

Terms of ServicePrivacy Policy