Start learning free

LESSON 23 OF 165 · MACHINE LEARNING: ANALYSIS PROJECTS

Which Products Sell? in Python

Practice

Which products bring the shop its money? orders.csv has one row per order line. Each line has a product, a quantity, the unit_price of one item and a status, which is "paid" or "cancelled". There is no money column yet. You make one by multiplying two columns, and pandas multiplies them row by row. Cancelled lines bring no money, so only the paid lines count.

One total per group: df.groupby("col") puts together the rows that share a value. Pick a column and call .sum(), and you get back a Series: one total per group, labelled with the group's name, in A to Z order. .sort_values(ascending=False) gives back the same Series with the biggest value first, and .index holds its labels in that order. Dividing a Series by one number divides every value in it, and .round(1) keeps 1 decimal. Here is an example on a small made-up table of tips:

tips = pd.DataFrame({"city": ["Cluj", "Berlin", "Cluj"], "amount": [10, 25, 5]})
by_city = tips.groupby("city")["amount"].sum()    # Berlin 25, Cluj 15
by_city = by_city.sort_values(ascending=False)    # Berlin first
pct = (by_city / by_city.sum() * 100).round(1)    # Berlin 62.5, Cluj 37.5
print(by_city.index[0])                           # Berlin

pd.DataFrame also takes a dict of Series. Each key becomes a column, and values with the same label go on the same row. .to_string() turns the whole table into text for print. Your script must print:

           revenue  share
product                  
Gift card    20750   36.4
Lamp         10614   18.6
Teapot        8338   14.6
Plant         6195   10.9
Mug           4344    7.6
Stapler       3276    5.7
Notebook      2793    4.9
Pen            668    1.2
Gift card sells the most: 20750 of 56978 in paid revenue, 36.4% of it.

Your task: orders.csv is already read into orders. Add a revenue column and keep only the paid lines. Add up the revenue per product and sort it biggest first. Work out each product's share of the total in percent and print both as one table. End with a sentence that names the best seller.


Assignment
Follow the Coding Tutorial to add up the paid revenue per product, rank the products with their shares, and print the answer in a sentence.


Hint
Keep only the paid lines before you group, so cancelled orders never reach a sum. Put the share math in parentheses before .round(1). To get one product's numbers, pick them by its name, like sales[best].


STEP 1 OF 10
    Ctrl + Enter to check

    Da Best Products 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