Thuta Learning
IntermediateData & Databasesintermediate

Universal Functions

Relax. We'll talk through this in plain words — no textbook voice.

Universal Functions, or ufuncs, are NumPy functions that quickly apply a single function to every element in an array. Examples include np.sqrt(), np.round(), np.sin(), np.exp(), np.log(), and more.

python
import numpy as np

values = np.array([1, 4, 9, 16])

print("Square root:", np.sqrt(values))
print("Power 2:", np.power(values, 2))
print("Rounded average:", np.round(values.mean(), 2))

np.sqrt(values) computes the square root of every element. np.power(values, 2) raises every element to the power of 2. values.mean() computes the average, and np.round(..., 2) rounds it to 2 decimal places.

You should see
Square root: [1. 2. 3. 4.] Power 2: [ 1 16 81 256] Rounded average: 7.5

Info

Using ufuncs tends to give you shorter code and better performance than writing a loop. That difference becomes more noticeable as your data grows.

Easy traps

  • Using np.log() on 0 or negative values can give you a warning or an invalid result. Keep the function's mathematical rules in mind.

Exercise

In machine learning preprocessing, ufuncs get used a lot for normalizing, scaling, and transforming data — things like applying a square root transform to sensor values, or rounding scores.

You'll know it worked when:

Universal Functions | Thuta Learning