Time for action – extracting elements from an array

Let's extract the even elements of an array:

  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 using our condition with the extract() function:
    print("Even numbers", np.extract(condition, a))

    This gives us the even numbers as required (np.extract(condition, a) is equivalent to a[np.where(condition)[0]]):

    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:

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

What just happened?

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

from __future__ import print_function
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