Time for action – extracting elements from an array

Let's extract the even elements from an array. Perform the following steps to do so:

  1. Create the array with the arange function.
    a = np.arange(7)
  2. Create the condition that selects the even elements.
    condition = (a % 2) == 0
  3. Extract the even elements based on our condition with the extract function.
    print "Even numbers", np.extract(condition, a)

    This gives us the even numbers, as required:

    Even numbers [0 2 4 6]
    
  4. Select non-zero values with the nonzero function.
    print "Non zero", np.nonzero(a)

    This prints all the non-zero values of the array, as follows:

    Non zero (array([1, 2, 3, 4, 5, 6]),)
    

What just happened?

We extracted the even elements from an array based on a Boolean condition with the NumPy extract function (see extracted.py).

import numpy as np

a = np.arange(7)
condition = (a % 2) == 0
print "Even numbers", np.extract(condition, a)
print "Non zero", np.nonzero(a)
..................Content has been hidden....................

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