Construct an array by executing a function over each coordinate in Numpy

NumpyServer Side ProgrammingProgramming

To construct an array by executing a function over each coordinate, use the numpy.fromfunction() method in Python Numpy. The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]])

The fromfunction() returns the result of the call to function is passed back directly. Therefore, the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would not match the shape parameter.

Steps

At first, import the required library −

import numpy as np

To construct an array by executing a function over each coordinate, use the numpy.fromfunction() method in Python Numpy −

print("Result\n",np.fromfunction(lambda a, b: a, (3, 3), dtype=float))
print("\nResult\n",np.fromfunction(lambda a, b: b, (3, 3), dtype=float))

Checking for array elements equality −

print("\nResult\n",np.fromfunction(lambda a, b: a == b, (4, 4), dtype=int))

Adding elements −

print("\nResult\n",np.fromfunction(lambda a, b: a + b, (5, 5), dtype=int))

Checking with greater than −

print("\nResult\n",np.fromfunction(lambda a, b: a > b, (5, 5), dtype=int))

Checking with less than −

print("\nResult\n",np.fromfunction(lambda a, b: a < b, (5, 5), dtype=int))

Example

import numpy as np

# To construct an array by executing a function over each coordinate, use the numpy.fromfunction() method in Python Numpy
print("Result\n",np.fromfunction(lambda a, b: a, (3, 3), dtype=float))
print("\nResult\n",np.fromfunction(lambda a, b: b, (3, 3), dtype=float))

# Checking for array elements equality
print("\nResult\n",np.fromfunction(lambda a, b: a == b, (4, 4), dtype=int))

# Adding elements
print("\nResult\n",np.fromfunction(lambda a, b: a + b, (5, 5), dtype=int))

# Checking with greater than
print("\nResult\n",np.fromfunction(lambda a, b: a > b, (5, 5), dtype=int))

# Checking with less than
print("\nResult\n",np.fromfunction(lambda a, b: a < b, (5, 5), dtype=int))

Output

Result
[[0. 0. 0.]
[1. 1. 1.]
[2. 2. 2.]]

Result
[[0. 1. 2.]
[0. 1. 2.]
[0. 1. 2.]]

Result
[[ True False False False]
[False True False False]
[False False True False]
[False False False True]]

Result
[[0 1 2 3 4]
[1 2 3 4 5]
[2 3 4 5 6]
[3 4 5 6 7]
[4 5 6 7 8]]

Result
[[False False False False False]
[ True False False False False]
[ True True False False False]
[ True True True False False]
[ True True True True False]]

Result
[[False True True True True]
[False False True True True]
[False False False True True]
[False False False False True]
[False False False False False]]
raja
Updated on 10-Feb-2022 09:44:31

Advertisements