Start learning free

LESSON 4 OF 165 · MACHINE LEARNING: NUMPY

Filter with True and False

Practice

Compare a numpy array with a number and numpy checks every item at once. You get back a new array of True and False values, one per item, in the same order. This True/False array is called a mask. With a plain list, [12, 7] > 10 is an error.

Put a mask inside square brackets and numpy keeps only the items at the True places. You get them back as a new, shorter array. In math, True counts as 1 and False as 0. So .sum() of a mask gives the number of Trues, and .mean() gives their share, a number from 0 to 1. Here is the idea on a stock array:

stock = np.array([0, 4, 0, 9])
in_stock = stock > 0
print(in_stock)         # [False  True False  True]
print(stock[in_stock])  # [4 9]
print(in_stock.sum())   # 2
print(in_stock.mean())  # 0.5

A mask only knows places: True at place 1, False at place 2, and so on. So a mask made from one array can pick from any other array of the same length, like the names that go with the prices.

The starting code has products (8 names) and prices (their 8 prices, in the same order), and it prints the prices. When you are done, the script prints:

Prices: [12  7 29  2 15 22  9 50]
Over 10: [ True False  True False  True  True False  True]
Prices over 10: [12 29 15 22 50]
Products over 10: ['Mug' 'Lamp' 'Plant' 'Teapot' 'Gift card']
How many: 5
Share: 0.625

Your task: keep prices > 10 in over_10 and print it. Use it to filter prices and then products. Then print how many prices are over 10 with .sum() and their share with .mean().


Assignment
Follow the Coding Tutorial to build the mask over_10, then use it to filter, count and measure the prices over 10.


Hint
The mask goes inside the square brackets of the array you filter. The same over_10 works on products because both arrays have 8 items in the same order. Call .sum() and .mean() on the mask itself, not on the prices.


STEP 1 OF 6
    Ctrl + Enter to check