Ufuncs exist in two flavors: unary ufuncs, which operate on a single input, and binary ufuncs, which operate on two inputs. We’ll see examples of both these types of functions here.
NumPy’s ufuncs feel very natural to use because they make use of Python’s native arithmetic operators. The standard addition, subtraction, multiplication, and division can all be used:
There is also a unary ufunc for negation, and a
** operator for exponentiation, and a
% operator for modulus:
In addition, these can be strung together however you wish, and the standard order of operations is respected:
Each of these arithmetic operations are simply convenient wrappers around specific functions built into NumPy; for example, the
+ operator is a wrapper for the
The following table lists the arithmetic operators implemented in NumPy:
Op. Equivalent ufunc Description + np.add Addition (e.g., 1 + 1 = 2) - np.subtract Subtraction (e.g., 3 - 2 = 1) - np.negative Unary negation (e.g., -2) * np.multiply Multiplication (e.g., 2 * 3 = 6) / np.divide Division (e.g., 3 / 2 = 1.5) // np.floor_divide Floor division (e.g., 3 // 2 = 1) ** np.power Exponentiation (e.g., 2 ** 3 = 8) % np.mod Modulus/remainder (e.g., 9 % 4 = 1)
Additionally there are Boolean/bitwise operators; we will explore these [prossimamente].
Just as NumPy understands Python’s built-in arithmetic operators, it also understands Python’s built-in absolute value function:
The corresponding NumPy ufunc is
np.absolute, which is also available under the alias
This ufunc can also handle complex data, in which the absolute value returns the magnitude:
NumPy provides a large number of useful ufuncs, and some of the most useful for the data scientist are the trigonometric functions.
The values are computed to within machine precision, which is why values that should be zero do not always hit exactly zero. Inverse trigonometric functions are also available: