We can create a universal function from a Python function with the NumPy frompyfunc
function, as follows:
def ultimate_answer(a):
So far, nothing special; we gave the function the name ultimate_answer
and defined one parameter, a
.
a
, with the zeros_like
function:result = np.zeros_like(a)
42
and return the result. The complete function should appear as shown, in the following code snippet. The flat
attribute gives us access to a flat iterator that allows us to set the value of the array:def ultimate_answer(a): result = np.zeros_like(a) result.flat = 42 return result
frompyfunc
; specify 1
as as number of input parameter followed by 1
as the number of output parameters:ufunc = np.frompyfunc(ultimate_answer, 1, 1) print "The answer", ufunc(np.arange(4))
The result for a one-dimensional array is shown as follows:
The answer [42 42 42 42]
We can do the same for a two-dimensional array by using the following code:
print "The answer", ufunc(np.arange(4).reshape(2, 2))
The output for a two dimensional array is shown as follows
The answer [[42 42] [[42 42] [42 42]]
We defined a Python function. In this function, we initialized to zero the elements of an array, based on the shape of an input argument, with the zeros_like
function. Then, with the flat
attribute of ndarray
, we set the array elements to the ultimate answer, 42
(see answer42.py
):
import numpy as np def ultimate_answer(a): result = np.zeros_like(a) result.flat = 42 return result ufunc = np.frompyfunc(ultimate_answer, 1, 1) print "The answer", ufunc(np.arange(4)) print "The answer", ufunc(np.arange(4).reshape(2, 2))