NumPy – Creating Universal Functions (ufunc)
In NumPy, ufunc (Universal Function) is a function that operates element-by-element on arrays.
We already know built-in ufuncs like:
-
np.add() -
np.multiply() -
np.sqrt()
But NumPy also allows you to create your own custom ufuncs.
This feature is powerful in NumPy because it lets you convert normal Python functions into high-performance array operations.
What is a Custom ufunc?
A custom ufunc is:
A user-defined function that behaves like a NumPy universal function and works on arrays element-by-element.
Why Create ufuncs?
✔ Reuse existing Python logic
✔ Apply functions to arrays efficiently
✔ Avoid writing loops
✔ Improve performance
✔ Work with large datasets
Import NumPy
import numpy as np
Method 1: Using np.frompyfunc()
This is the easiest way to create a ufunc.
Example 1: Custom Addition Function
import numpy as np
def add(x, y):
return x + y
ufunc_add = np.frompyfunc(add, 2, 1)
result = ufunc_add([1, 2, 3], [4, 5, 6])
print(result)
Output:
[5 7 9]
Explanation:
-
2→ number of input arguments -
1→ number of output values - Converts Python function into ufunc
Example 2: String Concatenation ufunc
import numpy as np
def combine(a, b):
return a + " " + b
ufunc_combine = np.frompyfunc(combine, 2, 1)
result = ufunc_combine(["Python", "NumPy"], ["Tutorial", "Guide"])
print(result)
Output:
['Python Tutorial' 'NumPy Guide']
Method 2: Using np.vectorize()
This method is more flexible and commonly used.
Example 3: Square Function
import numpy as np
def square(x):
return x * x
vec_square = np.vectorize(square)
result = vec_square([1, 2, 3, 4])
print(result)
Output:
[ 1 4 9 16]
Example 4: Even or Odd Check
import numpy as np
def check_even(x):
return "Even" if x % 2 == 0 else "Odd"
vec_check = np.vectorize(check_even)
result = vec_check([1, 2, 3, 4, 5])
print(result)
Output:
['Odd' 'Even' 'Odd' 'Even' 'Odd']
Difference: frompyfunc vs vectorize
| Feature | frompyfunc | vectorize |
|---|---|---|
| Speed | Faster | Slower |
| Output type | Object array | Maintains type |
| Use case | General ufunc creation | Easy Python wrapping |
| Flexibility | Medium | High |
Broadcasting with Custom ufunc
import numpy as np
def multiply(x, y):
return x * y
ufunc_mul = np.vectorize(multiply)
a = np.array([1, 2, 3])
b = 10
print(ufunc_mul(a, b))
Output:
[10 20 30]
Real-World Use Cases
Custom ufuncs are useful in:
📊 Data Processing
- Custom transformations
- Feature engineering
🧠 Machine Learning
- Activation functions
- Data normalization
📈 Finance
- Custom indicators
- Risk calculations
🧪 Scientific Computing
- Simulation models
- Physics formulas
Advantages of Custom ufuncs
✔ Works on arrays directly
✔ Reduces loops
✔ Improves readability
✔ Easy to integrate
✔ Reusable logic
Common Mistake
❌ Using loops instead of ufunc
result = []
for x in data:
result.append(x * x)
✅ Correct way
np.vectorize(lambda x: x*x)(data)
Summary
Creating ufuncs in NumPy allows you to convert normal Python functions into efficient array-based operations.
Both frompyfunc() and vectorize() make it easy to extend functionality in NumPy.
Conclusion
Custom ufuncs are powerful tools for developers working in Python. They help you write cleaner, faster, and more scalable code for data processing, AI, and analytics.


0 Comments