Time for action – extracting elements from an array
Let's extract the even elements of an array:
- Create the array with the
arange()
function:a = np.arange(7)
- Create the condition that selects the even elements:
condition = (a % 2) == 0
- 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 toa[np.where(condition)[0]]
):Even numbers [0 2 4 6]
- 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...