NumPy Universal Functions

NumPy provides built-in universal functions such as math, trigonometric, comparison, bit-twiddling, exponential, statistical, and linear algebra, making them a powerful tool for data analysis in Python.

Universal functions are a key feature of the NumPy library. A universal function is a function that operates on ndarrays in an element-by-element fashion, supporting array broadcasting and several other features.

Universal functions ar also called ufunc. Features of ufunc are;

Element-wise Operation:

Iniversal Functions functions operate element-wise on the whole array, producing an array. Universal Functions avoid the need for explicit loops making them very efficient. Avoiding loops produces a cleaner and more readable code. The element-wise operation on arrays is essential for numerical computations in Python.

Efficiency:

NumPy Universal Functions are optimized for performance. They are implemented in C, allowing for faster execution compared to standard Python lists. This is particularly beneficial for large datasets, making NumPy a preferred choice in data science and machine learning applications.

The ufunc allow the programmer to perform mathematical computations on arrays efficiently.

Universal Function (ufunc) Examples

Below are few examples of ufunc:

FunctionDescriptionExample
np.sinComputes the sine of each elementnp.sin(np.array([0, np.pi/2, np.pi]))
np.cosComputes the cosine of each elementnp.cos(np.array([0, np.pi/2, np.pi]))
np.addAdds two arrays element-wisenp.add(np.array([1, 2]), np.array([3, 4]))

Available Universal Functions

There are currently more than 60 universal functions defined in numpy on one or more types, covering a wide variety of operations.

For more details, click on the following link:

https://numpy.org/doc/stable/reference/ufuncs.html#available-ufuncs

Various Universal Functions Operations

The variety of universal function operations are:

  • Math operations: Examples: add(x1, x2), subtract(x1, x2), etc.
  • Trigonometric functions: All trigonometric functions use radians when an angle is called for. The ratio of degrees to radians is  180 debrees/ pi. Examples: sin(x, out), cos(x, out)
  • Bit-twiddling functions: These function all require integer arguments and they manipulate the bit-pattern of those arguments. Examples: bitwise_and(x1, x2), bitwise+or(x1, x2) etc
  • Comparison functions: Examples: greater(x1, x2), less(x1, x2), etc.
  • Floating functions: these functions work element-by-element over an array, returning an array output. Examples: isfinite(x, out), isinf(x, out), etc.

Custom Functions

In addition to NumPy built-in universal functions, you can create your own custom functions. You can use the custom functions to create NumPy arrays. The procedure to create your custom ufunc is the following:

Define a function just as you would do in Python stating the desired function name of your choosing.

  • Define the function’s functionality
  • Followed by a return statment
  • Use the fromfunc() method to convert your function into a ufunc.

In the main program, call the function named in the above steps using fromfunction() method.

NumPy fromfunction() Syntax

The following is fromfunc() syntax:

numpy.fromfunction(function, shape, dtype=float, **kwargs)

ParameterDescription
functionFunction name.  The name of the function you defined. The function is callable.
shapeshape is a tuple of integers that defines the output array’s dimensions. The length of this tuple determines the number of dimensions.
dtypedtype specifies the data type of the returned array.
dtype defaults to float (Optional)

Program Example of fromfunc() Method

The following program illustrates how to define custom functions:

# PROGRAM NAME: custom-functions.py
import numpy as np
#
# Define fromfunction function to create a 1-D array of dimension 5
# with each elment as multiple of 2
def array1d(i):
    return i*2
#
# Call "array1d".
arr = np.fromfunction(array1d, (5, ), dtype = int)
print("Array created by function 'array1d; is: \n", arr)
print()
####### End of 1-D array #####
# Define a function for sum of co-ordinates.
def sum_coord(x, y):
    return x + y
# 
# Create a 4x4 2-D array using function "sum_coord".
# Call function "sum_coord"
array2d = np.fromfunction(sum_coord, (4, 4), dtype=int)
print("4X4 2-D Array created by function 'array2d' is: \n", array2d)
print()
###### End of 4X4 2-D array using function "sum_coord" #######
# Define a function for sum of indices
def sum_indices(i, j):
    return (i + j)

# Call function "sum_indices"
# Create a 2-D 3x4 array using function "sum_indices".
array2d_sum = np.fromfunction(sum_indices, (3, 4), dtype=int)
print("Indices sum of 3x4 2-D array using function 'sum_indices' is:", array2d_sum)
print()
####### End of 3X4 array using function function "sum_indices" ########

# Define a function "arr2d"
def arr2d(x,y):
    return 10 * x + y

# Call function "arr2d"
# Create a 2D array with 5 rows and 4 columns using function "arr2d"
result = np.fromfunction(arr2d, (5, 4), dtype = int)
print("2D array created by function 'arr2d' is: \n, result ")
print()
####### End of 5X4 array using function function "arr_2d" ########

# Define a function using trigommetrical functions.
def arr_trig(a, b):
    return np.sin(a) + np.cos(b)

arr_t = np.fromfunction(arr_trig, (4, 4))
print("The result of trigonometrical function 'arr_trig' is: \n", arr_t)

The following is the output of the fromfunction() program:

Array created by function ‘array1d; is:
[0 2 4 6 8]

4X4 2-D Array created by function ‘array2d’ is:
[[0 1 2 3]
[1 2 3 4]
[2 3 4 5]
[3 4 5 6]]

Indices sum of 3×4 2-D array using function ‘sum_indices’ is: [[0 1 2 3]
[1 2 3 4]
[2 3 4 5]]

2D array created by function ‘arr2d’ is:
, result

The result of trigonometrical function ‘arr_trig’ is:
[[ 1. 0.54030231 -0.41614684 -0.9899925 ]
[ 1.84147098 1.38177329 0.42532415 -0.14852151]
[ 1.90929743 1.44959973 0.49315059 -0.08069507]
[ 1.14112001 0.68142231 -0.27502683 -0.84887249]]

Verified by MonsterInsights