TExcelTAD
Home › NumPy › NumPy Array Filter

NumPy Array Filter

Filtering builds a new array from only the elements you want. In NumPy you filter with a boolean index list (a mask): an array of True/False values of the same length. Elements under True are kept, elements under False are dropped.

python · try it yourself
import numpy as np

ages = np.array([15, 22, 37, 9, 64])
keep = np.array([False, True, True, False, True])
print(ages[keep])
[22 37 64]

Creating the mask from a condition

Writing masks by hand is rare. Normally a comparison creates them for you, element by element:

python · try it yourself
import numpy as np

ages = np.array([15, 22, 37, 9, 64])
adult = ages >= 18
print(adult)
print(ages[adult])
print(ages[ages < 18])         # usually written inline
print("number of adults:", adult.sum())   # True counts as 1
[False  True  True False  True]
[22 37 64]
[15  9]
number of adults: 3

Because True counts as 1, mask.sum() tells you how many elements match and mask.mean() tells you the fraction that match.

Combining conditions

Combine masks with the element-wise operators & (and), | (or) and ~ (not). Because of Python's operator precedence, wrap each comparison in parentheses:

python · try it yourself
import numpy as np

temps = np.array([-3, 4, 12, 19, 25, 31, 8])
print(temps[(temps > 10) & (temps < 30)])   # pleasant
print(temps[(temps < 0) | (temps > 30)])    # extreme
print(temps[~(temps > 10)])                 # not above 10
[12 19 25]
[-3 31]
[-3  4  8]

Warning: Python's and/or keywords don't work on arrays. temps > 10 and temps < 30 raises "The truth value of an array with more than one element is ambiguous". Use & and | instead.

Filtering with a mask from another array

A mask built from one array can filter a parallel array of the same length. This is how you query records:

python · try it yourself
import numpy as np

products = np.array(["pen", "laptop", "mug", "phone", "lamp"])
prices = np.array([2.5, 999.0, 8.0, 649.0, 35.0])
in_stock = np.array([True, False, True, True, True])

affordable = (prices < 100) & in_stock
print(products[affordable])
print("over 100:", products[prices > 100])
['pen' 'mug' 'lamp']
over 100: ['laptop' 'phone']

Filtering 2-D arrays

A mask on a 2-D array returns a 1-D result, because the kept elements no longer form a rectangle. To keep whole rows, build a 1-D mask over the rows from one column:

python · try it yourself
import numpy as np

# Each row: [student id, test score]
results = np.array([[101, 72],
                    [102, 45],
                    [103, 88],
                    [104, 59]])

print(results[results > 70])        # elements > 70 anywhere (1-D)
passed = results[:, 1] >= 60        # mask over rows
print(results[passed])              # whole rows kept
[101  72 102 103  88 104]
[[101  72]
 [103  88]]

The first result also contains the student ids (101, 102, …), because they are larger than 70 too. Filtering the whole table rarely makes sense when columns mean different things; filter rows by the relevant column instead.

Changing values with a mask

Masks also work on the left side of an assignment, which is a quick way to clean data. Here every negative reading (a sensor error) becomes 0:

python · try it yourself
import numpy as np

readings = np.array([3.2, -1.0, 4.8, -0.5, 2.1])
readings[readings < 0] = 0
print(readings)

clipped = np.clip(np.array([3, 15, -4, 8]), 0, 10)   # limit to 0..10
print(clipped)
[3.2 0.  4.8 0.  2.1]
[ 3 10  0  8]

np.clip(a, low, high) is a ready-made shortcut for the "replace values outside a range" pattern.

Test yourself

What is np.array([5, 10, 15])[np.array([True, False, True])]?

  1. [5 15]
  2. [10]
  3. [True False True]
  4. [5 10 15]

Which expression correctly selects values of a between 1 and 5 (exclusive)?

  1. a[a > 1 and a < 5]
  2. a[(a > 1) & (a < 5)]
  3. a[a > 1 & a < 5]
  4. a[1 < a < 5]

What does (a > 0).sum() compute?

  1. The sum of positive values
  2. The number of positive values
  3. A boolean
  4. The index of the first positive