Universal Functions-NumPy-Python
Universal functions are a powerful tool for performing mathematical operations on NumPy arrays. They are vectorized, which means that they operate on all elements of an array at once. This makes them much faster than looping over the elements of an array and performing the operation manually.
Here is an example of how to use the add() universal function:
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
z = np.add(x, y)
print(z)
This code will print the following output:
[5 7 9]
The z array contains the elements of x added to the corresponding elements of y.
Another example, the sum() ufunc sums all the elements in an array, and the abs() ufunc returns the absolute value of each element in an array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Sum all the elements in the array
print(np.sum(arr))
# Output: 15
# Find the absolute value of each element in the array
print(np.abs(arr))# Output: [1, 2, 3, 4, 5]
Here are the universal functions (ufuncs) in NumPy and their usage:
- abs(): Computes the absolute value of all elements in an array.
- add(): Adds two or more arrays element-wise.
- arccos(): Computes the inverse cosine of all elements in an array.
- arccosh(): Computes the inverse hyperbolic cosine of all elements in an array.
- arcsin(): Computes the inverse sine of all elements in an array.
- arcsinh(): Computes the inverse hyperbolic sine of all elements in an array.
- arctan(): Computes the inverse tangent of all elements in an array.
- arctanh(): Computes the inverse hyperbolic tangent of all elements in an array.
- ceil(): Rounds all elements in an array up to the nearest integer.
- cos(): Computes the cosine of all elements in an array.
- cosh(): Computes the hyperbolic cosine of all elements in an array.
- exp(): Computes the exponential of all elements in an array.
- floor(): Rounds all elements in an array down to the nearest integer.
- log(): Computes the natural logarithm of all elements in an array.
- log10(): Computes the base-10 logarithm of all elements in an array.
- maximum(): Returns the maximum value of all elements in an array.
- minimum(): Returns the minimum value of all elements in an array.
- power(): Performs exponentiation on all elements in an array.
- round(): Rounds all elements in an array to the nearest integer.
- sin(): Computes the sine of all elements in an array.
- sinh(): Computes the hyperbolic sine of all elements in an array.
- sqrt(): Computes the square root of all elements in an array.
- tan(): Computes the tangent of all elements in an array.
- tanh(): Computes the hyperbolic tangent of all elements in an array.
- trunc(): Truncates all elements in an array to the nearest integer.
These are just a few of the many ufuncs available in NumPy. You can find a complete list of ufuncs in the NumPy documentation.
Comments
Post a Comment