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. Kenya's Data Protection Act for Data Scientists
Bonaventure OgetoBy Bonaventure Ogeto|Updated November 3, 2026

Last checked 3 November 2026

Kenya's Data Protection Act for Data Scientists

Kenya's Data Protection Act 2019 treats pseudonymised data as still personal, because someone holding the key can link it back. Anonymised data, where people can no longer be identified, is outside the Act's focus. In pandas, hash phone numbers with a secret salt, generalise dates and amounts, then check k-anonymity.

In this article

  1. 1. The problem: a Safaricom statement on your laptop
  2. 2. What the Act and the ODPC say, in plain words
  3. 3. Anonymising an M-Pesa-like dataset in pandas
  4. 4. Check k-anonymity before you share
  5. 5. Habits that keep you out of trouble

The problem: a Safaricom statement on your laptop

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

Picture a client sending you an export of 50,000 M-Pesa payments for analysis. Each row has a phone number, a name, an amount and a timestamp. You want to build a model. Every one of those rows is a real person's money trail.

This guide covers two things. First, what the law says about handling that file. Second, how to strip it down in pandas so your analysis can go ahead with less risk. It is general information and not legal advice. Ask a lawyer or the regulator about your own case.

It does not repeat the full compliance walk-through in our Data Protection Act guide for AI builders. Read that for registration, rights and fines. For where this skill fits in a career, see the data science career guide for Kenya.

What the Act and the ODPC say, in plain words

The Data Protection Act, 2019 is on Kenya Law. The Office of the Data Protection Commissioner (ODPC) publishes guidance and the Act's text at odpc.go.ke. Section numbers below were checked on 3 November 2026 against a published copy of the Act, so confirm them on Kenya Law before you quote them.

  • Personal data (section 2). Any information relating to an identified or identifiable natural person. A phone number plus a timestamp can identify someone. So can a rare amount at a small shop.
  • Anonymisation (section 2). The removal of personal identifiers from personal data so that the data subject is no longer identifiable. If this truly holds, the data stops being personal data in practice.
  • Pseudonymisation (section 2). Processing personal data so it can no longer be attributed to a specific person without additional information, which must be kept separately and protected. The data is still personal, because the key exists.
  • Principles (section 25). Among them: collect for a specified purpose, keep only what you need (data minimisation), keep it accurate, and store it no longer than necessary.
  • Data protection by design and by default (section 41). Build safeguards in from the start. Pseudonymisation is named as one such measure. By default, process only what each purpose needs.
  • Impact assessment (section 31). Where processing is likely to carry high risk to people's rights and freedoms, an assessment comes first.
  • Transfers abroad (sections 48 and 49). Moving personal data out of Kenya needs safeguards, and sensitive data needs the subject's consent too. Uploading a raw file to a foreign cloud notebook counts.

Two lessons for a data scientist. Hashing a phone number is pseudonymisation, not anonymisation, so the Act still applies. And minimising early, by dropping columns you do not need, is the cheapest compliance step there is.

If you want to learn to work with such data responsibly, our Data Science programme in Nairobi builds its projects on M-Pesa style data.

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Anonymising an M-Pesa-like dataset in pandas

For example, imagine a made-up file called payments.csv with the columns phone, name, amount, timestamp and till_area. None of it is real. The steps are in order of how much each reduces risk.

Step 1: drop what you do not need

import pandas as pd

df = pd.read_csv("payments.csv")
df = df.drop(columns=["name"])   # you never model on names

Step 2: replace phone numbers with a salted hash

A plain hash of a Kenyan phone number is easy to reverse. The list of possible numbers is short enough that an attacker can hash every one of them. A secret salt (a random string you keep outside the dataset) blocks that.

import hmac, hashlib, os

SALT = os.environ["PHONE_SALT"].encode()   # keep out of the repo

def pseudonym(phone):
    return hmac.new(SALT, str(phone).encode(), hashlib.sha256).hexdigest()[:16]

df["customer_id"] = df["phone"].map(pseudonym)
df = df.drop(columns=["phone"])

The same phone always maps to the same customer_id, so you can still count repeat customers. Store the salt separately and restrict who can read it. This is the "additional information, kept separately" the Act's definition talks about.

Step 3: generalise

Exact timestamps and exact amounts make people findable. Coarsen them.

df["timestamp"] = pd.to_datetime(df["timestamp"])
df["hour_band"] = df["timestamp"].dt.floor("3h")
df["day"] = df["timestamp"].dt.date
df["amount_band"] = pd.cut(
    df["amount"],
    bins=[0, 100, 500, 1000, 5000, 20000, 150000],
)
df = df.drop(columns=["timestamp", "amount"])

You lose precision, so ask what the analysis needs. A fraud model may need exact amounts. A footfall study does not. Decide per purpose, not once for all.

Check k-anonymity before you share

k-anonymity is a simple test. Choose the columns someone could combine to pick out a person, called quasi-identifiers. Here: till_area, day and amount_band. Every combination should appear at least k times, often 5. A combination that appears once is a person who can be found.

quasi = ["till_area", "day", "amount_band"]
sizes = df.groupby(quasi, observed=True).size()
print("smallest group:", sizes.min())
risky = sizes[sizes < 5]
print(len(risky), "combinations appear fewer than 5 times")

If risky combinations exist, generalise more (weekly instead of daily, wider amount bands, bigger areas) or drop those rows. Run the check again until the smallest group reaches your k.

Know the limits. k-anonymity does not stop someone who already knows facts about a target, and a very rare event, such as one large payment at a small stage, can still stand out. For data you will publish, take advice. For data you only analyse inside your team, pseudonymisation plus minimisation plus access control is a sensible baseline.

The same habits belong in the team data quality checklist, where "what is personal" is one of four governance lines. For the full analysis workflow on a statement, see analysing an M-Pesa statement in Python.

Habits that keep you out of trouble

  • Ask for the smallest extract that answers the question, not the full database.
  • Do the anonymising inside the client's environment where you can, then export.
  • Keep the salt and any lookup file away from the analysis folder and out of Git.
  • Do not paste raw rows into public chatbots or foreign notebooks.
  • Write down what you removed and why. A short note beats a long memory.
  • When you only need practice data, use Kenyan open datasets instead of anyone's real payments.

Our Data Science programme in Nairobi teaches these habits next to the models, because a model built on data you were not allowed to hold helps nobody.

Key Takeaways

  • ✓Pseudonymised data is still personal data under the Act; anonymised data should no longer identify anyone.
  • ✓Drop columns you do not need before anything else.
  • ✓Hash phone numbers with a secret salt kept outside the dataset.
  • ✓Generalise dates and amounts, then check that every group has at least k rows.

Frequently Asked Questions

Is a hashed phone number anonymous?
No. It is pseudonymised. Anyone holding the salt, or able to guess numbers, can link it back, so the Data Protection Act still treats it as personal data.
Do I need ODPC registration to analyse client data?
Registration depends on whether you act as a controller or processor and on your size and sector. Check the ODPC website or ask a lawyer for your case.
What k should I use for k-anonymity?
Five is a common starting point, higher for sensitive data. There is no single legal number in the Act, so choose based on risk and document it.
Can I use real M-Pesa data for a portfolio project?
Only your own statement, with consent from anyone named in it, or data that is truly anonymised. Otherwise use synthetic or open data.

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

Or we build it with your team

Related guides

  • AI vs Machine Learning vs Data Science: The Difference
  • Best Data Science Courses in Kenya (2026): Fees, Length, Who Each Suits
  • Can You Learn Data Science Without a Maths Background?

Keep reading

AI and Data Privacy for Kenyan Developers: The Data Protection Act Basics

If you are building AI features that process personal data in Kenya, the Data Protection Act 2019 applies to you. This guide explains the key requirements in plain language, what they mean for developers, and practical steps to stay compliant without hiring a legal team on day one.

Read more

Data Quality and Governance Checklist for Kenyan Teams

Six checks a finance, sales or operations team can run on its own spreadsheets before anyone trusts a number, plus a plain table of who owns each one.

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

Kenyan Open Datasets: Where to Find Real Data to Practise On

Where to find real Kenyan data for practice projects: eight sources, what each holds, the file format and the date we opened it.

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