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:

  1. Using np.vectorize() (Python-level, slower, but easy)

  2. 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 @vectorize decorator or Cython.

  • Can handle scalars, arrays, multiple inputs, and different output types.


🎯 Practice Exercises

  1. Create a ufunc that computes f(x) = x^3 – x + 2 for an array.

  2. Create a ufunc that classifies numbers as even/odd.

  3. Create a ufunc with two inputs that computes x^2 + y^2.

You may also like...