"Customers who bought this also bought…" starts with one count: for each pair of products, how many customers bought both. With the last lesson's 0/1 customer by product table, one line counts every pair at once.
Turn and multiply: matrix.T gives back the table turned on its side, with one row per product and one column per customer. @ multiplies two tables: each cell of the result is a row of the left one times a column of the right one, cell by cell, added up. Since 1 × 1 is 1 and anything × 0 is 0, one product's row times another product's column counts the customers with a 1 in both. Here is a small example with 3 customers and 2 products:
a = np.array([[1, 0], [1, 1], [0, 1]])
print(a.T @ a)
# [[2 1]
# [1 2]]
The result has one row and one column per product, and it is a mirror: row A, column B equals row B, column A. On the diagonal, a product meets itself, which gives its number of buyers. To read one product's partners, take its column and .drop() its own row: drop(label) gives back the Series without that label. Then sort_values(ascending=False) and head(3) give the top 3.
Your program must print:
product Gift card Lamp Mug Notebook Pen Plant Stapler Teapot product Gift card 197 90 76 59 67 79 58 76 Lamp 90 116 36 30 29 71 31 35 Mug 76 36 103 27 29 36 23 64 Notebook 59 30 27 96 49 27 52 30 Pen 67 29 29 49 98 25 48 30 Plant 79 71 36 27 25 111 24 28 Stapler 58 31 23 52 48 24 92 26 Teapot 76 35 64 30 30 28 26 107 product Gift card 76 Mug 64 Lamp 35
Your task: matrix is already made. Count the customers of every pair of products in together and print it. Then put the Teapot's column, without the Teapot itself, in with_teapot, sort it from the largest count down and print its first 3.
Assignment
Follow the Coding Tutorial to count the products bought together and find the 3 bought most often with the Teapot.
Hint
Turn the left table, not the right one: products must end up on both sides. Without .drop("Teapot"), the Teapot comes first in its own list, with 107.
Free plan: 30 tutor messages. PRO is unlimited.
