Universal Functions are functions that operates on NumPy ndarrays in an element-by-element fashion, supporting array broadcasting and several other features.
NumPy provides built-in universal functions (ufunc) 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.
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.
Broadcasting:
The broadcating term describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python.
Universal Function (ufunc) Examples
Below are few examples of ufunc:
| Function | Description | Example |
|---|---|---|
| np.sin | Computes the sine of each element | np.sin(np.array([0, np.pi/2, np.pi])) |
| np.cos | Computes the cosine of each element | np.cos(np.array([0, np.pi/2, np.pi])) |
| np.add | Adds two arrays element-wise | np.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)
| Parameter | Description |
|---|---|
| function | Function name. The name of the function you defined. The function is callable. |
| shape | shape is a tuple of integers that defines the output array’s dimensions. The length of this tuple determines the number of dimensions. |
| dtype | dtype specifies the data type of the returned array. dtype defaults to float (Optional) |
Program Example: fromfunc() Method
The following program illustrates how to define custom functions:
import numpy as np
print("Program name: fromfunction_array1d2d3d. \n")
# fromfunction for 1-D array with elments as multiple of 2
print("Define a function 'elem2x' to generate a1-D array")
print("with elements multiple of 2. \n")
def elem2x(i):
return i*2
#
arr1d= np.fromfunction(elem2x, (5, ), dtype = int)
print("1-D array with 5 elements created by function 'elem2x' is:")
print(arr1d)
print("End of section 1_D array by fromfinction 'elem2x' ----\n")
print("-------------------------------------")
# Define a function for sum of co-ordinate
def sumxy(x, y):
return x + y
#
# Create a 4x4 2-D array using function "sumxy"
arr_sum_xy = np.fromfunction(sumxy, (4, 4), dtype=int)
print("4X4 2-D Array created by function 'sumxy' is: \n")
print(arr_sum_xy)
print("End of section 4x4 2D array by funcrion 'sumxy'. \n")
print("--------------------------------------")
#
# Define a function for sum of indices
def sum_indices(i, j):
return (i + j)
#
# Create a 2-D 3x4 array using function sum_indices.
array_2d_sum_ind = np.fromfunction(sum_indices, (3, 4), dtype=int)
print("Indices sum of 3x4 2-D array using function 'sum_indices' is: ")
print(array_2d_sum_ind)
print("End of section 3x4 2D array by funcrion 'sum_indices'. \n")
print("---------------------------------------")
# Define a function for sum 10x + y
def sum10xpy(x,y):
return 10 * x + y
#
# Create a 5x4 2D array using function "sum10x+y"
arr2d10xpy = np.fromfunction(sum10xpy, (5, 4), dtype = int)
print("2D array created by function 'arr2d10xpy' is: ")
print(arr2d10xpy)
#
print("End of section 5x4 2D array with function 10x+y. \n")
print("---------------------------------------")
# Define a function for sum x + y =z
def sumxyz(x, y, z):
return(x + y+ z)
#
# Create a 3D array with 2 depth, 3 rows, and 4 column
array3d = np.fromfunction(sumxyz, (2, 3, 4), dtype = int)
print("3D array created by function 'sumxyz' is: ")
print(array3d)
The following are the “fromfunctionarray1d2d3d” program’s output:
Program name: fromfunction_array1d2d3d.
Define a function ‘elem2x’ to generate a1-D array
with elements multiple of 2.
1-D array with 5 elements created by function ‘elem2x’ is:
[0 2 4 6 8]
End of section 1_D array by fromfinction ‘elem2x’ —-
4X4 2-D Array created by function ‘sumxy’ is:
[[0 1 2 3]
[1 2 3 4]
[2 3 4 5]
[3 4 5 6]]
End of section 4×4 2D array by funcrion ‘sumxy’.
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]]
End of section 3×4 2D array by funcrion ‘sum_indices’.
2D array created by function ‘arr2d10xpy’ is:
[[ 0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]]
End of section 5×4 2D array with function 10x+y.
3D array created by function ‘sumxyz’ is:
[[[0 1 2 3]
[1 2 3 4]
[2 3 4 5]]
[[1 2 3 4]
[2 3 4 5]
[3 4 5 6]]]