Skip to content

NumPy Universal Functions (ufuncs)

What are ufuncs?

A ufunc (universal function) is a function that operates element-wise on arrays and is optimized for speed.

Examples:

  • np.sqrtnp.sqrt, np.expnp.exp, np.lognp.log
  • np.sinnp.sin, np.cosnp.cos
  • np.maximumnp.maximum, np.minimumnp.minimum

They are faster and cleaner than Python loops.

Example: sqrt

sqrt
import numpy as np
 
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr))
sqrt
import numpy as np
 
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr))

Common math ufuncs

math
import numpy as np
 
x = np.array([1.0, 2.0, 3.0])
print(np.exp(x))
print(np.log(x))
print(np.log10(x))
math
import numpy as np
 
x = np.array([1.0, 2.0, 3.0])
print(np.exp(x))
print(np.log(x))
print(np.log10(x))

Trigonometric ufuncs

trig
import numpy as np
 
angles = np.array([0, np.pi/2, np.pi])
print(np.sin(angles))
print(np.cos(angles))
trig
import numpy as np
 
angles = np.array([0, np.pi/2, np.pi])
print(np.sin(angles))
print(np.cos(angles))

Comparison ufuncs

max-min
import numpy as np
 
a = np.array([1, 10, 3])
b = np.array([2, 5, 4])
 
print(np.maximum(a, b))
print(np.minimum(a, b))
max-min
import numpy as np
 
a = np.array([1, 10, 3])
b = np.array([2, 5, 4])
 
print(np.maximum(a, b))
print(np.minimum(a, b))

Working with NaN values

Some ufuncs have NaN-safe variants.

nan
import numpy as np
 
arr = np.array([1.0, np.nan, 3.0])
print(np.nanmean(arr))
print(np.nansum(arr))
nan
import numpy as np
 
arr = np.array([1.0, np.nan, 3.0])
print(np.nanmean(arr))
print(np.nansum(arr))

Ufuncs + broadcasting

Ufuncs naturally work with broadcasting.

broadcast
import numpy as np
 
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sqrt(mat))
broadcast
import numpy as np
 
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sqrt(mat))

Next

Continue to: Stacking and Splitting Arrays to combine and break arrays along different axes.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Create a NumPy Array

Exercise 2 โ€“ Array Shape and Reshape

Exercise 3 โ€“ Array Arithmetic

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did