Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Preparing data with pandas

By the end of this chapter, you'll be able to

  • Group and aggregate lines with groupby
  • Cross two dimensions with a pivot table
  • Compute percentage shares and changes
  • Avoid the average of averages

Sales lines

Here is an extract of the cooperative's sales (fictitious figures):

import pandas as pd

sales = pd.DataFrame({
    "month":   ["sep", "sep", "sep", "oct", "oct", "oct", "oct", "nov", "nov"],
    "market":  ["Koutiala", "Bamako", "Sikasso", "Koutiala", "Bamako", "Bamako", "Sikasso", "Koutiala", "Bamako"],
    "product": ["butter", "soap", "butter", "butter", "butter", "soap", "soap", "soap", "butter"],
    "kg":      [120, 80, 60, 100, 150, 70, 40, 90, 160],
})
print(sales.groupby("market")["kg"].sum().sort_values(ascending=False))
market
Bamako      460
Koutiala    310
Sikasso     100
Name: kg, dtype: int64

groupby("market") sorts the lines by market, ["kg"].sum() adds up the kilos of each group, and sort_values sorts the result: exactly what a sorted bar chart needs.

Crossing two dimensions

To see each market's trend month by month, we build a pivot table: one row per month, one column per market.

import pandas as pd

sales = pd.DataFrame({
    "month":   ["sep", "sep", "sep", "oct", "oct", "oct", "oct", "nov", "nov"],
    "market":  ["Koutiala", "Bamako", "Sikasso", "Koutiala", "Bamako", "Bamako", "Sikasso", "Koutiala", "Bamako"],
    "kg":      [120, 80, 60, 100, 150, 70, 40, 90, 160],
})
table = sales.pivot_table(index="month", columns="market", values="kg", aggfunc="sum", fill_value=0)
table = table.reindex(["sep", "oct", "nov"])
print(table)
market  Bamako  Koutiala  Sikasso
month                            
sep         80       120       60
oct        220       100       40
nov        160        90        0

fill_value=0 fills the cells with no sale, and reindex puts the months back in calendar order (otherwise pandas sorts them alphabetically: nov, oct, sep). Each column of this table can become a line.

Each column of the table becomes a line: the chart is now easy to plot.

Step 5 of 5
Text description of the animation
  1. The data arrives sale by sale: impossible to draw as it is.
  2. We group the lines that share the same month and the same market.
  3. In each group, we add up the kilos: two sales in Bamako in October make 220 kg.
  4. We put the months back in calendar order, not alphabetical order.
  5. Each column of the table becomes a line: the chart is now easy to plot.

Shares and changes

Two calculations come up all the time: the share of each category in the total, and the change from one period to the next.

import pandas as pd

monthly_total = pd.Series({"sep": 260, "oct": 360, "nov": 250})
print((monthly_total.pct_change() * 100).round(1))

by_product = pd.Series({"butter": 630, "soap": 240})
print((by_product / by_product.sum() * 100).round(1))
sep     NaN
oct    38.5
nov   -30.6
dtype: float64
butter    72.4
soap      27.6
dtype: float64

pct_change() computes the change from the previous row (NaN, "not a number", for the first month, which has no previous month). Dividing by the sum gives each product's share: butter accounts for 72.4% of the kilos sold.

Mini-lab: sales by product and monthPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the month's summary

From the sales table at the start of the chapter, compute for October only: the total kilos, the kilos per product, and each product's share as a percentage, rounded to one decimal.

Hint 1
First filter the lines with sales[sales["month"] == "oct"].
Hint 2
Once groupby("product")["kg"].sum() is computed, divide it by its own sum.
Show the solution and common mistakes
import pandas as pd

sales = pd.DataFrame({
    "month":   ["sep", "sep", "sep", "oct", "oct", "oct", "oct", "nov", "nov"],
    "product": ["butter", "soap", "butter", "butter", "butter", "soap", "soap", "soap", "butter"],
    "kg":      [120, 80, 60, 100, 150, 70, 40, 90, 160],
})
october = sales[sales["month"] == "oct"]
by_product = october.groupby("product")["kg"].sum()
print("total:", october["kg"].sum())
print(by_product)
print((by_product / by_product.sum() * 100).round(1))
total: 360
product
butter    250
soap      110
Name: kg, dtype: int64
product
butter    69.4
soap      30.6
Name: kg, dtype: float64

Common mistakes:

  • Computing the shares on the total of the whole year instead of October's total: the percentages no longer add up to 100%.
  • Forgetting the filter and grouping all the lines: you get three months of sales, presented as October's.

Summary

  1. 1groupby groups the lines sharing a value, then sum, mean or count summarise them.
  2. 2pivot_table crosses two dimensions, for example months as rows and markets as columns.
  3. 3Put categories back in their natural order, such as calendar months, with reindex.
  4. 4pct_change gives changes; dividing by the sum gives shares.
  5. 5An average of averages is wrong when groups differ in size: weight them.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.