Start learning free

LESSON 116 OF 165 · MACHINE LEARNING: RECOMMENDERS

A Customer by Product Table in Python

Practice

Every recommender in this chapter starts from the same picture of the shop: a table with one row per customer and one column per product. Each cell says whether that customer bought that product. With 8 products, the whole table fits on the screen.

Building it: pd.crosstab(rows, columns) takes two columns of the same data and gives back a table that counts the lines of each pair. It has one row per value of the first column and one column per value of the second. For example, how many paid and cancelled lines each product has:

by_status = pd.crosstab(orders["product"], orders["status"])

Counts are not what a recommender needs: four Teapot lines don't make someone four times the Teapot fan. clip(upper=1) gives back the table with every number above 1 replaced by 1, so each cell means bought (1) or not (0). .shape is the pair (rows, columns). .to_numpy() gives back the values as a plain numpy array, and its .mean() is the share of 1s: how full the table is.

Your program must print:

product      Gift card  Lamp  Mug  Notebook  Pen  Plant  Stapler  Teapot
customer_id
1                    3     1    3         0    1      1        0       4
2                    1     2    0         0    0      1        0       0
3                    1     0    1         1    1      0        1       1
4                    1     0    0         0    2      0        2       0
5                    0     0    0         3    1      0        0       0
product      Gift card  Lamp  Mug  Notebook  Pen  Plant  Stapler  Teapot
customer_id
1                    1     1    1         0    1      1        0       1
2                    1     1    0         0    0      1        0       0
3                    1     0    1         1    1      0        1       1
4                    1     0    0         0    1      0        1       0
5                    0     0    0         1    1      0        0       0
Shape: (292, 8)
Filled: 0.394

Your task: make matrix from the paid lines with pd.crosstab, with customers as rows and products as columns, and print its first five rows. Clip it to 0/1 and print them again. Then print its shape and how full it is, rounded to 3 digits.


Assignment
Follow the Coding Tutorial to build the customer by product table and measure how full it is.


Hint
Rows first: paid["customer_id"], then paid["product"]. Keep the clipped table in matrix again, so that everything after it uses the 0/1 version.


STEP 1 OF 6
    Ctrl + Enter to check

    Rec Matrix in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free