Time for action – creating universal function

We can create a universal function from a Python function with the NumPy frompyfunc function, as follows:

  1. 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.

  2. Create a result consisting of all zeros, that has the same shape as a, with the zeros_like function:
    result = np.zeros_like(a)
  3. 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. 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
  4. Create a universal function with 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]]
    

What just happened?

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))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset