Profiling and exploring data
Measure before you change. Profiling turns a vague sense that 'the data's a bit messy' into a precise list of problems.
Learning objectives
- Profile structure, types, missing values and duplicates
- Use value counts to find inconsistent categories
- Find impossible values and statistical outliers
- Check validity of formats such as dates
- Write a data quality report
- Check consistency across columns and rows
- Profile a set of documents for emptiness, duplication and age
Setup: the practice 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"],
})2.1 Profile before you change anything
Data profiling means systematically measuring a dataset: its size, types, missing values, distributions, unique values and relationships. It tells you what needs fixing — and gives you a baseline to compare against after cleaning.
2.2 A first look
Python · structural profileprint(customers.shape) # (rows, columns)
customers.info() # types and non-null counts
print(customers.isna().sum()) # missing values per column
print(customers.isna().mean().round(2)) # share missing
print(customers.duplicated().sum(), "fully duplicated rows")
print(customers["customer_id"].duplicated().sum(), "repeated IDs")
Read the types as carefully as the counts. signup_date and churned are stored as text, not as dates and true/false values. That is a finding in itself: it usually means the column contains something that couldn't be read as the proper type.
2.3 Categorical columns
for col in ["country", "churned"]:
print(customers[col].value_counts(dropna=False), "\n")
Value counts instantly expose inconsistent spellings and unexpected categories.
2.4 Numerical columns and outliers
print(customers[["age", "monthly_spend"]].describe())
# Rule-based checks: values outside what's possible
print(customers[(customers["age"] < 16) | (customers["age"] > 110)])
# Statistical check: the IQR rule flags unusually large or small values
q1, q3 = customers["monthly_spend"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(customers[(customers["monthly_spend"] < low) | (customers["monthly_spend"] > high)])
A value can be unusual but real — a genuine big-spending customer. Use rules (an age of 230 is impossible) to find errors, and statistics to find values worth investigating. Ask someone who knows the business before deleting anything.
2.5 Validity checks
Python · which dates don't parse?parsed = pd.to_datetime(customers["signup_date"], format="%Y-%m-%d", errors="coerce")
bad_dates = customers.loc[parsed.isna() & customers["signup_date"].notna(), "signup_date"]
print(bad_dates) # "04/02/2025" (different format) and "2025-13-01" (invalid month)
2.6 Visual profiling
import matplotlib.pyplot as plt
customers["monthly_spend"].plot(kind="hist", bins=20, title="Monthly spend")
plt.show()
customers.boxplot(column="age")
plt.show()
Histograms reveal skew and spikes (e.g. lots of zeros or a default like 999); box plots show outliers at a glance. Here the histogram is nearly useless — one bar on the left and one far to the right — which is itself the message: a single extreme value is squashing everything else.
2.7 Write a data quality report
Summarise each issue: the column, the problem, how many rows, the likely cause, and the proposed fix. Share it with the data's owners — they often know causes you can't see (a system migration, a form default, a manual entry step).
Python · the report as a tablereport = pd.DataFrame([
{"column": "customer_id", "issue": "repeated ID", "rows": int(customers["customer_id"].duplicated().sum()), "proposed fix": "drop exact duplicate"},
{"column": "signup_date", "issue": "missing or unparseable", "rows": int(parsed.isna().sum()), "proposed fix": "ask source system owner about formats"},
{"column": "country", "issue": "inconsistent spellings", "rows": int((~customers["country"].isin(["UK", "IE"])).sum()), "proposed fix": "map to UK / IE codes"},
{"column": "age", "issue": "missing or impossible", "rows": int((customers["age"].isna() | ~customers["age"].between(16, 110)).sum()), "proposed fix": "set impossible to missing; decide on filling"},
{"column": "monthly_spend", "issue": "missing or extreme", "rows": int((customers["monthly_spend"].isna() | (customers["monthly_spend"] > high)).sum()), "proposed fix": "check 12,000 with finance"},
])
print(report.to_string(index=False))
Counting the rows matters. "Some ages are wrong" starts an argument; "4 of 10 ages are missing or impossible" starts a fix.
2.8 Checks across columns and rows
Some problems only show up when you compare fields with each other. A column can look fine on its own while the row makes no sense.
Python · cross-field checks# Do repeated IDs carry the same details, or do they conflict?
repeats = customers[customers["customer_id"].duplicated(keep=False)]
print(repeats)
print("Conflicting copies:", repeats.drop_duplicates().shape[0] > repeats["customer_id"].nunique())
# Rows that fail more than one check deserve a closer look
problems = pd.DataFrame({
"bad_date": parsed.isna(),
"bad_age": customers["age"].isna() | ~customers["age"].between(16, 110),
"bad_spend": customers["monthly_spend"].isna() | (customers["monthly_spend"] > high),
})
customers_checked = customers.assign(problems=problems.sum(axis=1))
print(customers_checked[customers_checked["problems"] >= 2])
Customer 103's two rows are identical, so one can simply be dropped. Had they disagreed (two different ages, say) you would need a rule for which to trust, such as the most recently updated record. Typical cross-field rules in real data: an end date before a start date, a delivery to a country you don't ship to, a refund larger than the order.
2.9 Profiling text and documents
The same habits apply to the documents behind an AI assistant (Module 1.7). You can't run describe() on a policy, but you can measure length, emptiness, duplication and age.
Python · profiling a small document setdocs = pd.DataFrame({
"title": ["Returns policy", "Returns policy (copy)", "Delivery times", "Price list 2024", "Price list 2026", "FAQ"],
"text": ["You can return items within 30 days.", "You can return items within 30 days.",
"UK delivery takes 2-3 working days. Ireland takes 4-6.", "Bamboo board: £19.99",
"Bamboo board: £24.99", ""],
"updated": pd.to_datetime(["2026-03-01", "2026-03-01", "2025-11-12", "2024-01-15", "2026-01-10", "2026-02-02"]),
})
docs["words"] = docs["text"].str.split().str.len()
print(docs[["title", "words", "updated"]])
print("Empty documents: ", docs.loc[docs["words"] == 0, "title"].tolist())
print("Exact duplicate text: ", docs.loc[docs["text"].duplicated() & (docs["words"] > 0), "title"].tolist())
print("Not updated since 2024:", docs.loc[docs["updated"] < "2025-01-01", "title"].tolist())
Three findings in six documents: an empty FAQ, a duplicated policy and an old price list sitting beside the current one. An assistant searching this folder could quote either price. Document collections in real organisations run to thousands of files, which is why these checks need to be code, not a read-through.
Write a function profile(df) that returns a DataFrame with one row per column showing its type, number missing, percentage missing and number of unique values.
Your turn# Write your code here, then press RunShow a solution
def profile(df):
return pd.DataFrame({
"dtype": df.dtypes.astype(str),
"missing": df.isna().sum(),
"missing_pct": (df.isna().mean() * 100).round(1),
"unique": df.nunique(dropna=True),
})
print(profile(customers))Systems often store a placeholder such as 0, 999 or "N/A" when a value is unknown. Run the starter code, then find which value in readings appears suspiciously often, and what share of the column it makes up.
Your turnrng = np.random.default_rng(3)
readings = pd.Series(np.where(rng.random(200) < 0.15, 999, rng.normal(50, 8, 200).round()))
# Find the suspicious value, then press RunShow a solution
rng = np.random.default_rng(3)
readings = pd.Series(np.where(rng.random(200) < 0.15, 999, rng.normal(50, 8, 200).round()))
counts = readings.value_counts()
print(counts.head(3))
print("Share that is the top value:", round(counts.iloc[0] / len(readings), 2))
# 999 appears far more often than any real reading: it is a placeholder for 'unknown',
# and would wreck an average if treated as a number.Key takeaways
- info(), isna() and duplicated() give a structural profile.
- value_counts exposes inconsistent categories.
- Rules find errors; statistics find values to investigate.
- Coercing dates reveals invalid and mixed formats.
- Share a data quality report with data owners.
- Some problems only appear when you compare fields with each other.
- Documents can be profiled too: length, duplicates and last-updated dates.