Mctaba Labs logo
BootcampData ScienceThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book CallApply

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
Mctaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • Coding Bootcamp in Nairobi
  • Data Science to AI Engineering
  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • Kids & Teens
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Data Science Guides
  • African Payments Reference
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Software & AI Studio
  • Our Work
  • Outcomes

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2026 Mctaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Data Science in Kenya
  3. Pandas Tutorial Using a Nairobi Shop's Sales Data
Bonaventure OgetoBy Bonaventure Ogeto|Updated November 3, 2026

Last checked 3 November 2026

Pandas Tutorial Using a Nairobi Shop's Sales Data

Load the sales CSV with read_csv, fix names and missing prices, add a revenue column, then use groupby to total by product and by day. Sort the product totals to see top sellers and use nsmallest on daily totals to find slow days. All steps are below on made-up rows.

In this article

  1. 1. The shop file we will use
  2. 2. Clean it: names, blanks and revenue
  3. 3. Group by product and by day
  4. 4. What to try next

The shop file we will use

McTaba runs coding and data bootcamps in Kenya. This guide is written to be useful whether or not you ever join one.

Imagine a kiosk near a Nairobi bus stage. The owner types each day's sales into a phone sheet: date, product, quantity, price. After a month she has a file with typos and a few blanks. That is the file we clean here, as one step on the data science career map.

These rows are made up for the tutorial. They are not real shop figures. Install pandas with pip install pandas. If Python is new to you, start with Python for data science for beginners.

import io
import pandas as pd

csv = """date,product,qty,unit_price
2026-10-01,Unga 2kg,12,190
2026-10-01,Milk 500ml,30,65
2026-10-01,Bread,20,
2026-10-02,unga 2kg,8,190
2026-10-02,Milk 500ml,25,65
2026-10-02,Sugar 1kg,10,170
2026-10-03,Bread,18,60
2026-10-03,Milk 500ml,2,65
2026-10-04,Unga 2kg,15,190
2026-10-04,Sugar 1kg,9,170
2026-10-04,Bread,22,60
2026-10-05,Milk 500ml,28,65
"""
df = pd.read_csv(io.StringIO(csv), parse_dates=["date"])
df.info()

With your own file, replace io.StringIO(csv) with "sales.csv". The info() call lists each column, its type and how many cells are filled. Here unit_price shows 11 of 12: one price is missing.

MethodQuestion it answers
read_csvHow do I get the file in?
info, isnaWhat is missing or the wrong type?
str.strip, str.capitalizeWhy is "unga 2kg" a separate product?
groupbyHow much per product or per day?
nsmallest, sort_valuesWhich are the best and worst?

Our Data Science to AI Engineering programme teaches pandas and data cleaning in phase 2, with weekly projects on Kenyan data.

Clean it: names, blanks and revenue

df["product"] = df["product"].str.strip().str.capitalize()

# fill a missing price with that product's usual price
df["unit_price"] = df.groupby("product")["unit_price"].transform(
    lambda s: s.fillna(s.median())
)
df["revenue"] = df["qty"] * df["unit_price"]

Two fixes happen here. Capitalising merges "unga 2kg" and "Unga 2kg" into one product. Then the blank bread price takes the median bread price, which is 60.

Filling a blank is a choice, not a fact. Ask the shop owner what happened that day. If you cannot ask, say in your notes that one price was filled.

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Group by product and by day

by_product = (df.groupby("product")[["qty", "revenue"]]
              .sum().sort_values("revenue", ascending=False))
print(by_product)

daily = df.groupby("date")["revenue"].sum()
print(daily.nsmallest(2))

The first table ranks products. On these rows, unga leads on shillings while milk leads on units. Those two lists answer different questions: what earns the most, and what the fridge must never run out of.

The second call prints the two slowest days. On this sample they are 3 and 5 October. A slow day is a prompt for a question: was it rain, a stock-out, or a day with no entry at all?

Which weekday is slow?

by_weekday = daily.groupby(daily.index.day_name()).mean()
print(by_weekday.round())

grid = df.pivot_table(index="date", columns="product",
                      values="qty", aggfunc="sum", fill_value=0)
print(grid)

Averaging by weekday needs weeks of data, not five days, before you trust it. The pivot table is the shopkeeper's view: one row per day, one column per product, a zero where nothing sold. A zero for milk on 4 October on this sample would be a stock-out worth asking about.

What to try next

Run the same code on a real month from a shop you know, with permission. Then try three things: plot daily with daily.plot(), save the cleaned table with df.to_csv("clean.csv"), and write two sentences a shop owner could act on.

Pandas also reads your own money records. Analyse your M-Pesa statement in Python uses the same cleaning steps on a PDF. To turn daily totals into a stock plan, go to forecasting a shop's stock from till data. If you prefer asking the data in SQL, see SQL for data analysis.

Want a classroom, mentors and a capstone? Read about our Data Science to AI Engineering programme: next intake 11 January 2027, KES 140,000.

Key Takeaways

  • ✓Inspect first with info(): missing cells and wrong types show up before they spoil a total.
  • ✓Clean names before grouping, or one product becomes two rows.
  • ✓groupby plus sort_values answers most shop questions: top sellers, slow days.
  • ✓Say what you filled or dropped. A cleaning choice is part of the answer.

Frequently Asked Questions

Is pandas hard to learn?
The core is small: read a file, clean columns, group and sort. Most shop questions need only groupby and sort_values. Practise on a file you care about, and the rest follows.
Why did my groupby print a Series, not a table?
Selecting one column after groupby returns a Series. Use double brackets, such as groupby("product")[["revenue"]], to get a table back.
How should I handle a missing price?
Ask the source first. If you cannot, fill it with the median for that product and write down that you did. Never fill silently.
Can I use pandas on Excel files?
Yes. pd.read_excel("sales.xlsx") works once the openpyxl package is installed. The cleaning and groupby steps are identical.

Learn data science on African data

KES 140,000

Data Science to AI Engineering: 5 months full time or 8 months part time, hybrid in Nairobi. Fraud, credit and M-Pesa data from Week 1, and every model deployed. Starts 11 January 2027.

See the Data Science programme

Need it live by next month? Our studio builds it

Related guides

  • Data Engineering Basics: Build a Pipeline with Airflow and Docker
  • Data Science Roadmap for Beginners: 6 Months, Week by Week
  • Data Science in Kenya: The Career Map from First Line of Python to First Job

Keep reading

Python for Data Science: Your First 30 Days

Thirty days, four weeks, one small script a week. Learn only the parts of Python that data work uses, with examples on made-up Kenyan shop data.

Read more

Analyse Your M-Pesa Statement in Python

Turn the PDF Safaricom emails you into a clean table, a spending breakdown and a chart, with code you can run on your own laptop.

Read more

Forecast a Shop's Stock from Till Data

Use a moving average, a weekday pattern and a month-end bump to forecast a shop's sales, then set a reorder point you can pin by the stockroom door.

Read more

SQL for Data Analysis: Queries You Will Use Every Week

Five query patterns cover most weekly analyst work. Each is shown on a made-up mobile money table, in PostgreSQL syntax.

Read more

Explore related topics

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

Tech Salary Data

Transparent salary data for tech roles in Africa and worldwide, updated regularly with real market research.

AI Skills & Tools

Practical AI knowledge for developers. Build your first agent, get good at RAG, and pick the right AI coding tools for real work.

Bonaventure Ogeto

Bonaventure Ogeto

Founder and CEO, Mctaba Labs

Software engineer for 8+ years. He runs a Nairobi studio that ships products on M-Pesa, WhatsApp and AI, and teaches what the studio ships. He holds a BSc in Mathematics and Computer Science.

More about the author