TExcelTAD
Home › NumPy › ufunc Create Function

ufunc Create Function

Sometimes NumPy doesn't have the exact element-wise function you need. You can turn an ordinary Python function into a ufunc with np.frompyfunc, or wrap it with the more convenient np.vectorize. Then it accepts arrays and applies itself to every element.

np.frompyfunc(function, nin, nout)

It needs three arguments:

Argument Meaning
function the Python function to wrap
nin number of input arguments
nout number of return values
python · try it yourself
import numpy as np

def shipping_cost(weight_kg, express):
    base = 5 if weight_kg <= 2 else 5 + (weight_kg - 2) * 1.5
    return base * 2 if express else base

shipping = np.frompyfunc(shipping_cost, 2, 1)
weights = np.array([1, 3, 6])
print(shipping(weights, False))
print(shipping(weights, np.array([True, False, True])))
print(type(shipping))
[5 6.5 11.0]
[10 6.5 22.0]
<class 'numpy.ufunc'>

Our function now works on arrays, and it even supports broadcasting (the scalar False is applied to every weight). But notice one thing: the result has dtype=object. frompyfunc always returns Python objects, so you usually convert with .astype(float):

python · try it yourself
import numpy as np

def shipping_cost(weight_kg, express):
    base = 5 if weight_kg <= 2 else 5 + (weight_kg - 2) * 1.5
    return base * 2 if express else base

shipping = np.frompyfunc(shipping_cost, 2, 1)
costs = shipping(np.array([1, 3, 6]), False)
print(costs.dtype)
print(costs.astype(float), costs.astype(float).sum())
object
[ 5.   6.5 11. ] 22.5

np.vectorize: friendlier, with a real dtype

np.vectorize does the same job but picks a proper output dtype (from the first result, or from otypes if you give it), keeps the function's name and docstring, and can be used as a decorator:

python · try it yourself
import numpy as np

@np.vectorize
def grade(score):
    """Turn a numeric score into a letter grade."""
    if score >= 90:
        return "A"
    if score >= 75:
        return "B"
    if score >= 60:
        return "C"
    return "F"

scores = np.array([[95, 72], [60, 81]])
print(grade(scores))
print(grade.__doc__)
[['A' 'C']
 ['C' 'B']]
Turn a numeric score into a letter grade.

With otypes you declare the output type yourself, which is safer when the first result might be misleading (for example an int where later results are floats):

python · try it yourself
import numpy as np

def safe_ratio(a, b):
    return a / b if b != 0 else 0

ratio = np.vectorize(safe_ratio, otypes=[float])
print(ratio(np.array([6, 5, 9]), np.array([3, 0, 4])))
[2.   0.   2.25]

Checking whether a function is a ufunc

python · try it yourself
import numpy as np

my_ufunc = np.frompyfunc(lambda x: x * 2, 1, 1)
my_vec = np.vectorize(lambda x: x * 2)

print(type(np.add) == np.ufunc)
print(type(my_ufunc) == np.ufunc)    # frompyfunc makes a real ufunc
print(type(my_vec) == np.ufunc)      # vectorize does not
if type(np.concatenate) != np.ufunc:
    print("np.concatenate is a normal function")
True
True
False
np.concatenate is a normal function

A word about speed

Neither frompyfunc nor vectorize makes your Python function fast: under the hood they still call it once per element. They are about convenience, not performance. When speed matters, try to express the logic with existing ufuncs and np.where/np.select:

python · try it yourself
import numpy as np

scores = np.array([95, 72, 60, 81, 40])
letters = np.select(
    [scores >= 90, scores >= 75, scores >= 60],   # conditions, checked in order
    ["A", "B", "C"],                              # matching choices
    default="F",
)
print(letters)
['A' 'C' 'C' 'B' 'F']

This gives the same letter grades as the grade function above, but runs entirely in compiled code.

Test yourself

What are the three arguments of np.frompyfunc?

  1. function, dtype, shape
  2. function, nin, nout
  3. name, inputs, outputs
  4. function, axis, out

What dtype does an array returned by a frompyfunc ufunc have?

  1. float64
  2. object
  3. int64
  4. The same as the input

Does np.vectorize make a Python function run at C speed?

  1. Yes, it compiles it
  2. No, it still calls the Python function for each element
  3. Only for integers
  4. Only with otypes