Ufuncs, or universal functions, are a feature of NumPy that allow you to perform element-wise operations on arrays. They are designed to operate on ndarrays in an efficient manner, applying a function to each element of the array.
Key Features of Ufuncs:
-
Element-wise Operations: Ufuncs apply operations to each element of the input arrays independently.
-
Broadcasting: Ufuncs support broadcasting, which allows them to work with arrays of different shapes during arithmetic operations.
-
Performance: Ufuncs are implemented in C, making them much faster than using Python loops for element-wise operations.
-
Types of Ufuncs: There are many built-in ufuncs in NumPy, such as
np.add,np.subtract,np.multiply,np.divide, and many more for mathematical functions likenp.sin,np.exp, etc.
Example:
Here's a simple example of using ufuncs in NumPy:
import numpy as np
# Create two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Use ufuncs to add the arrays
result = np.add(a, b)
print(result) # Output: [5 7 9]
In this example, np.add is a ufunc that adds corresponding elements of the arrays a and b.
