Time for action – creating universal function
We can create a universal function from a Python function with the NumPy frompyfunc
function, as follows:
Define a Python function that answers the ultimate question to the universe, existence, and the rest (it's from The Hitchhiker's Guide to the Galaxy; if you haven't read it, you can safely ignore this).
def ultimate_answer(a):
So far, nothing special; we gave the function the name
ultimate_answer
and defined one parameter,a
.Create a result consisting of all zeros, that has the same shape as
a
, with thezeros_like
function:result = np.zeros_like(a)
Now set the elements of the initialized array to the answer
42
and return the result. The complete function should appear as shown, in the following code snippet. Theflat
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
Create a universal function with
frompyfunc
; specify...