Create Your Own ufunc
π οΈ Creating Your Own ufunc in NumPy
NumPy allows you to create custom universal functions (ufuncs), which can then operate element-wise on NumPy arrays just like built-in ufuncs.
There are two main ways:
-
Using
np.vectorize()(Python-level, slower, but easy) -
Using NumPy C-API or Numba (fast, compiled, advanced)
Here, we focus on np.vectorize(), which is sufficient for most Python use-cases.
β
1. Using np.vectorize()
np.vectorize() wraps a Python function so it can be applied element-wise to arrays.
-
Works element-wise
-
Can handle any Python function
β 2. Using Lambda Function
-
Compact and convenient for simple functions
β
3. Using otypes Parameter
You can specify output type with otypes to avoid type inference issues.
β 4. Using Multiple Inputs
-
Supports multiple array inputs
-
Element-wise operations are performed
β 5. Example: Conditional Function ufunc
-
Useful for categorical transformations
π§ Notes
-
np.vectorize()is not truly compiled; itβs essentially a for loop in Python. -
For high-performance ufuncs, consider Numbaβs
@vectorizedecorator or Cython. -
Can handle scalars, arrays, multiple inputs, and different output types.
π― Practice Exercises
-
Create a ufunc that computes f(x) = x^3 – x + 2 for an array.
-
Create a ufunc that classifies numbers as even/odd.
-
Create a ufunc with two inputs that computes
x^2 + y^2.
