Documenting and governing data
Good data work leaves evidence. This module covers the documentation, protection and governance that make datasets trustworthy — and legally defensible.
Learning objectives
- Write a datasheet for a dataset
- Maintain lineage and versions
- Apply data protection principles to AI data
- Pseudonymise identifiers
- Explain Article 10 and automate data quality checks
- Compare a new batch of data with a reference
- List the governance needed for documents used by AI assistants
Setup: the cleaned data from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport pandas as pd
import numpy as np
customers = pd.DataFrame({
"customer_id": [101, 102, 103, 103, 104, 105, 106, 107, 108, 109],
"signup_date": ["2025-01-04", "04/02/2025", "2025-02-10", "2025-02-10", "2025-03-15",
"2025-13-01", "2025-04-02", None, "2025-05-20", "2025-06-01"],
"country": ["UK", "United Kingdom", "uk", "uk", "Ireland", "UK", "IE", "UK", "U.K.", "UK"],
"age": [34, 29, None, None, 41, 230, 38, 27, -1, 52],
"monthly_spend": [42.5, 18.0, 63.2, 63.2, None, 25.0, 12000.0, 31.4, 22.0, 47.9],
"churned": ["no", "yes", "No", "No", "no", "yes", "no", "YES", "no", "no"],
})
clean = customers.drop_duplicates().reset_index(drop=True)
country_map = {"uk": "UK", "united kingdom": "UK", "u.k.": "UK", "ireland": "IE", "ie": "IE"}
clean["country"] = clean["country"].str.strip().str.lower().map(country_map).fillna(clean["country"])
clean["churned"] = clean["churned"].str.strip().str.lower().map({"yes": True, "no": False})
dates = pd.to_datetime(clean["signup_date"], format="%Y-%m-%d", errors="coerce")
alt = pd.to_datetime(clean["signup_date"], format="%d/%m/%Y", errors="coerce")
clean["signup_date"] = dates.fillna(alt)
clean.loc[(clean["age"] < 16) | (clean["age"] > 110), "age"] = np.nan
clean["age_missing"] = clean["age"].isna()
clean["age"] = clean["age"].fillna(clean["age"].median())
clean.loc[clean["monthly_spend"] > 1000, "monthly_spend"] /= 1006.1 Document your data: datasheets
A datasheet for a dataset records what anyone using it needs to know. Key sections:
- Motivation: why it was created and by whom
- Composition: what each record represents, size, fields, known gaps
- Collection: sources, time period, consent and legal basis
- Preparation: cleaning and labelling steps (your decision log)
- Uses: intended uses — and uses it is not suitable for
- Maintenance: owner, update schedule, version history
Part of a datasheet can be produced from the data itself, which keeps it accurate as the data changes:
Python · the factual part of a datasheet, generated from the datadatasheet = {
"name": "customers_clean",
"version": "1.0 (2026-11-30)",
"records": f"{len(clean)} customers, one row each",
"fields": ", ".join(clean.columns),
"period": f"sign-ups {clean['signup_date'].min().date()} to {clean['signup_date'].max().date()}",
"known gaps": f"{int(clean['signup_date'].isna().sum())} missing sign-up dates, "
f"{int(clean['monthly_spend'].isna().sum())} missing spend, "
f"{int(clean['age_missing'].sum())} ages filled with the median",
"make-up": clean["country"].value_counts().to_dict(),
"not suitable for": "anything about customers outside the UK and Ireland; too small for modelling",
"owner": "Customer analytics team",
}
for key, value in datasheet.items():
print(f"{key:17} {value}")
The sections on motivation, consent and intended use can't be generated: someone has to write them. Those are the sections people most often need, so don't leave them blank.
6.2 Lineage and versioning
Data lineage records where data came from and every transformation applied. Versioning means you can always say exactly which data trained a given model — essential for debugging, audits and reproducing results. Save cleaning code (not just cleaned files), and give each dataset release a version and date.
6.3 Data protection
If your data relates to identifiable people, UK GDPR (or EU GDPR) applies throughout the AI lifecycle:
| Principle | In practice for AI data |
|---|---|
| Lawfulness, fairness, transparency | A lawful basis for using data to train or run AI; tell people in privacy notices |
| Purpose limitation | Check that training a model is compatible with why the data was collected |
| Data minimisation | Only the fields you need; pseudonymise IDs; drop direct identifiers |
| Accuracy | Everything in this course! |
| Storage limitation | Retention periods for raw and derived datasets |
| Security | Access controls, encryption, audit logs |
Special category data (such as health or ethnicity) needs extra conditions; a Data Protection Impact Assessment is often required. The ICO's guidance on AI and data protection is the UK reference point.
6.4 Pseudonymisation in code
Python · replace IDs with salted hashesimport hashlib, os
SALT = os.environ.get("ID_SALT", "set-a-secret-salt") # keep the salt secret and separate
def pseudonymise(value):
return hashlib.sha256((SALT + str(value)).encode()).hexdigest()[:16]
clean["customer_key"] = clean["customer_id"].map(pseudonymise)
model_data = clean.drop(columns=["customer_id"])
print(model_data[["customer_key", "country", "age"]].head(4))
Pseudonymised data is still personal data under GDPR, because it can be re-linked with the key — but it reduces risk.
The salt is a secret piece of text mixed in before hashing. Without it, anyone could hash the numbers 1 to 100,000 themselves and match the results to your keys. Try changing the salt in the cell and running it again: every key changes.
6.5 The EU AI Act: data governance for high-risk AI
For high-risk AI systems, Article 10 of the EU AI Act requires training, validation and testing data to be subject to appropriate data governance and management practices, and to be relevant, sufficiently representative and, to the best extent possible, free of errors and complete in view of the intended purpose — with attention to possible biases. The practices in this course — profiling, cleaning logs, representativeness checks, documentation — are how organisations evidence that. See EU AI Act Fundamentals, Module 4.
The dates have moved: following the 2026 Digital Omnibus on AI, these obligations apply to most stand-alone high-risk systems from 2 December 2027. The extra time is for getting practices like these in place, and evidence of them takes months to build up, so it is not a reason to wait.
6.6 Data quality is continuous
Data keeps changing after a model is deployed. Automate checks in data pipelines (types, ranges, allowed values, missing rates, row counts), alert on failures, and monitor for drift — shifts in the data your model sees compared with what it was trained on.
Python · simple automated checks for a pipelinedef check(df):
problems = []
if df["customer_key"].duplicated().any(): problems.append("duplicate customers")
if not df["age"].between(16, 110).all(): problems.append("age out of range")
if df["monthly_spend"].isna().mean() > 0.05: problems.append("too many missing spend values")
if not set(df["country"].dropna()) <= {"UK", "IE"}: problems.append("unexpected country code")
return problems
print(check(model_data) or "All checks passed")
The check fails, and it should: one spend value in nine is still missing, which is more than the 5% the rule allows. A failing check is the system working. The decision it forces — fix the source, fill the value, or relax the rule and say why — is the one nobody made in Module 3.
6.7 Checking a new batch of data
The checks above test fixed rules. Drift is different: every value can be valid while the overall picture shifts. Compare each new batch with a reference you trust.
Python · this month's data against the referencenew_batch = pd.DataFrame({
"country": ["UK", "UK", "IE", "FR", "UK", "FR", "UK", "IE", "FR", "UK"],
"age": [22, 25, 31, 24, 27, 23, 29, 26, 21, 28],
"monthly_spend": [15.0, None, 22.5, None, 18.0, 12.0, None, 20.0, 16.5, 19.0],
})
def drift_report(reference, new):
return pd.DataFrame({
"reference": [reference["age"].mean().round(1), reference["monthly_spend"].mean().round(1),
round(reference["monthly_spend"].isna().mean(), 2), sorted(reference["country"].unique())],
"new batch": [new["age"].mean().round(1), new["monthly_spend"].mean().round(1),
round(new["monthly_spend"].isna().mean(), 2), sorted(new["country"].unique())],
}, index=["average age", "average spend", "share of spend missing", "countries"])
print(drift_report(clean, new_batch).to_string())
Customers are younger, spend less, a new country has appeared and far more spend values are missing. No single row is "wrong", yet a model trained on the reference data is now being asked about a different kind of customer. The response is the same as for any data quality finding: find out why (a new market? a broken form field?) before deciding what to do.
6.8 Governing the data behind AI assistants
When an organisation connects an AI assistant to its documents, those documents become the data that matters, and they need the same governance as any training set:
- An owner and a review date for every source, so out-of-date content is found and removed
- Permissions that carry through — if a member of staff can't open a document, the assistant shouldn't quote it to them
- One current version of each policy, with old versions archived out of the assistant's reach
- Personal data kept out unless there is a reason and a lawful basis for it to be there
- A record of what is sent where — which data goes to which AI provider, under what terms, and whether it is kept or used for training
- A route for corrections, so that when the assistant gives a wrong answer someone fixes the source document, not just the reply
None of this is new. It is the content of this module — documentation, lineage, protection, continuous checks — applied to documents as well as tables.
Add a rule to check() that reports a problem if the most recent signup_date is more than 90 days before a given today date (stale data). Test it with today = "2026-11-30".
Your turntoday = "2026-11-30"
# Write check_fresh(df, today, max_days=90), then press RunShow a solution
def check_fresh(df, today, max_days=90):
age_days = (pd.Timestamp(today) - df["signup_date"].max()).days
return [f"newest record is {age_days} days old"] if age_days > max_days else []
print(check(model_data) + check_fresh(model_data, "2026-11-30"))
# Timeliness is one of the six dimensions, and the easiest to automate.The starter code lists the sources an AI assistant uses. Print the sources with no owner, the sources not reviewed in the past year (before 2025-12-01), and any that contain personal data without a recorded reason.
Your turnregister = pd.DataFrame({
"source": ["Returns policy", "Price list", "Old support tickets", "Staff handbook"],
"owner": ["Customer service", None, "Customer service", "HR"],
"last_review": pd.to_datetime(["2026-09-01", "2024-01-15", "2025-06-30", "2026-10-10"]),
"personal_data": [False, False, True, True],
"reason": [None, None, None, "needed for HR queries; staff only"],
})
# Print the three lists, then press RunShow a solution
register = pd.DataFrame({
"source": ["Returns policy", "Price list", "Old support tickets", "Staff handbook"],
"owner": ["Customer service", None, "Customer service", "HR"],
"last_review": pd.to_datetime(["2026-09-01", "2024-01-15", "2025-06-30", "2026-10-10"]),
"personal_data": [False, False, True, True],
"reason": [None, None, None, "needed for HR queries; staff only"],
})
print("No owner: ", register.loc[register["owner"].isna(), "source"].tolist())
print("Review overdue: ", register.loc[register["last_review"] < "2025-12-01", "source"].tolist())
print("Personal data, no reason:", register.loc[register["personal_data"] & register["reason"].isna(), "source"].tolist())
# Each list is a job for a named person, not a job for the AI.Key takeaways
- Datasheets record motivation, composition, collection, preparation, uses and maintenance.
- Version data and save cleaning code to make models reproducible.
- UK GDPR applies throughout the AI lifecycle; minimise and pseudonymise.
- Article 10 requires governed, representative, error-checked data for high-risk AI.
- Automate checks and monitor drift.
- A failing check is the system working: it forces a decision.
- Documents used by AI assistants need owners, review dates, permissions and a route for corrections.