NumPy: Universal Functions (ufunc)
Last updated: 2026-08-26
1. What You'll Learn
- ❶ What is a ufunc — universal function
- ❷ ufunc attributes: nin, nout, ntypes, types
- ❸ ufunc methods: reduce, accumulate, outer, reduceat
- ❹ Creating custom ufuncs with
np.frompyfunc
2. Key Concepts
(1) What Is a ufunc
A ufunc (universal function) is a C-level function that operates element-wise on ndarrays. All arithmetic operators call ufuncs under the hood.
PYTHON
import numpy as np
# Operators are ufuncs
print(np.add) # ufunc 'add'
print(np.multiply) # ufunc 'multiply'
print(np.sin) # ufunc 'sin'
# ufunc attributes
print(np.add.nin) # 2 (number of inputs)
print(np.add.nout) # 1 (number of outputs)
print(np.add.ntypes) # number of supported type combinations
(2) ufunc Methods
PYTHON
a = np.array([1, 2, 3, 4, 5])
# reduce: apply repeatedly to reduce to single value
print(np.add.reduce(a)) # 15 (sum)
print(np.multiply.reduce(a)) # 120 (product)
# accumulate: running result
print(np.add.accumulate(a)) # [1 3 6 10 15]
# outer: apply to all pairs
print(np.multiply.outer([1, 2, 3], [10, 20, 30]))
# [[10 20 30]
# [20 40 60]
# [30 60 90]]
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example: ufunc attributes (Difficulty ⭐)
PYTHON
import numpy as np
print("add:", np.add)
print("multiply:", np.multiply)
print("sin:", np.sin)
print(f"np.add.nin: {np.add.nin}")
print(f"np.add.nout: {np.add.nout}")
print(f"np.add.ntypes: {np.add.ntypes}")
Output:
TEXT 📖 Display onlyadd: ufunc 'add' multiply: ufunc 'multiply' sin: ufunc 'sin' np.add.nin: 2 np.add.nout: 1 np.add.ntypes: 22
▶ Example: ufunc reduce and accumulate (Difficulty ⭐⭐)
PYTHON
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# reduce: apply repeatedly to get a single value
print("add.reduce:", np.add.reduce(a))
print("multiply.reduce:", np.multiply.reduce(a))
# accumulate: running result
print("add.accumulate:", np.add.accumulate(a))
print("multiply.accumulate:", np.multiply.accumulate(a))
Output:
TEXT 📖 Display onlyadd.reduce: 15 multiply.reduce: 120 add.accumulate: [ 1 3 6 10 15] multiply.accumulate: [ 1 2 6 24 120]
▶ Example: ufunc outer (Difficulty ⭐⭐)
PYTHON
import numpy as np
# Outer product: multiply every pair
x = np.array([1, 2, 3])
y = np.array([10, 20, 30, 40])
print("outer:\n", np.multiply.outer(x, y))
# Comparison outer
a = np.array([1, 3, 5])
b = np.array([2, 4, 6])
print("greater.outer:\n", np.greater.outer(a, b))
Output:
TEXT 📖 Display onlyouter: [[ 10 20 30 40] [ 20 40 60 80] [ 30 60 90 120]] greater.outer: [[False False False] [ True False False] [ True True False]]
Q What's the difference between a ufunc and a regular function?
A A ufunc operates element-wise, handles broadcasting, type promotion, and output buffering automatically. It's implemented in C, making it much faster than Python functions.
Q How do I create a custom ufunc?
A Use
np.frompyfunc(func, nin, nout) to wrap a Python function. The resulting ufunc handles broadcasting but is still Python-level, so performance is limited.Q What is
reduceat?A
np.add.reduceat(a, indices) applies reduce at specific slices — useful for segmented sums or grouped operations.❓ FAQ
Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.
📖 Summary
- ufuncs are C-level element-wise functions:
np.add,np.multiply,np.sin, etc. - Attributes:
nin,nout,ntypes,typesdescribe the ufunc interface - Methods:
reduce(single value),accumulate(running),outer(all pairs),reduceat(segments) - ufuncs are the engine behind NumPy's vectorization and broadcasting
📝 Exercises
-
Beginner (Difficulty ⭐): List the attributes of
np.add— nin, nout, ntypes, types. Explain what each means. -
Intermediate (Difficulty ⭐⭐): Use
np.add.reduceto sum an array,np.add.accumulateto compute running sum, andnp.multiply.outerto create a multiplication table. -
Advanced (Difficulty ⭐⭐⭐): Use
np.frompyfuncto create a custom ufunc that returns the larger of two numbers. Apply it to two arrays and compare withnp.maximum.