0Pricing
Pandas & NumPy Academy · Lesson

Universal Functions (ufuncs)

Apply built-in element-wise functions such as np.sqrt, np.abs, np.exp, and np.log to arrays without writing loops.

What Are ufuncs?

Universal functions (ufuncs) run a math operation on every element of an array at once, in fast compiled C — far quicker than a Python loop. ⚡

import numpy as np

a = np.array([1.0, 4.0, 9.0, 16.0])
print(np.sqrt(a))  # [1. 2. 3. 4.]
# Equivalent Python loop would be hundreds of times slower

Math ufuncs: sqrt, exp, log

All your favourite math functions are ufuncs: np.sqrt, np.exp, np.log, and more. They apply to whole arrays at once and handle edge cases gracefully.

import numpy as np

a = np.array([0.0, 1.0, 2.0, 3.0])
print(np.exp(a))         # [1.    2.718 7.389 20.086]
print(np.log(np.exp(a))) # [0. 1. 2. 3.]
print(np.log2(np.array([1, 2, 4, 8])))  # [0. 1. 2. 3.]

All lessons in this course

  1. Universal Functions (ufuncs)
  2. Aggregation Functions
  3. Broadcasting Rules
  4. Boolean Masking and Fancy Indexing
← Back to Pandas & NumPy Academy