Sub topic 2
Collecting and Understanding Your Data
This chapter covers the step between framing the problem and exploring the data: deciding what data you need, gathering it, and checking that you understand what each row and column means. It assumes you can write basic Python, can use pandas DataFrames, know the mean, variance and distributions, and know what supervised learning is. The previous chapter defined the target. Here you check whether the data can support that target.
Why this step comes first
A model can only learn patterns that exist in its data. If the data does not match the question, no later step fixes it. Most expensive failures in a project trace back to the data: the target was recorded differently than you assumed, the rows are not the unit you want to predict, or the data was collected in a way that will not match the future.
Collection and understanding means answering four questions:
- What does one row represent?
- Where did each column come from, and when was it known?
- Does the sample look like the cases the model will see in use?
- Is there enough data, with enough variety, to learn the pattern?
Define the unit of analysis
The unit of analysis is what one row stands for. In a churn project it might be one customer, one customer-month, or one subscription. The choice changes the model and how you split the data later.
Suppose you predict whether a customer cancels next month. If you use one row per customer-month, the same customer appears in many rows. A random split would then put some of their rows in training and some in test. The model can recognize the customer rather than learn a general pattern. The splitting chapter covers the fix, but you must notice the repeated entities here.
Write the unit down as a sentence: "One row is one customer on the first day of a month, with the label showing whether they cancelled in that month."
Find sources and record their limits
Tabular data usually comes from some mix of these sources:
- Operational databases, which store what the business needs to run, not what a model needs.
- Event logs and clickstreams, which need aggregating into per-entity features.
- Files from other teams or vendors, such as CSV or Excel exports.
- Public datasets and APIs.
- Manual labeling, where people assign the target.
For each source, record who owns it, how often it updates, and how it was produced. A short data dictionary is enough. It lists each column's name, type, meaning, units, allowed values, and source.
| Column | Type | Meaning | Source | Known at prediction time? |
|---|---|---|---|---|
| customer_id | string | Unique customer key | CRM | Yes |
| signup_date | date | Account creation date | CRM | Yes |
| monthly_spend | float | Spend in the last 30 days, in USD | Billing | Yes |
| support_tickets | int | Tickets opened in the last 90 days | Helpdesk | Yes |
| cancelled | int | 1 if the customer cancelled in the next month | CRM | No, this is the target |
The last column is the one people skip. A feature that is not available when you make a real prediction cannot be used. A column filled in after the outcome, such as "cancellation reason", will make the model look excellent in testing and fail in use. This is a form of leakage, which a later chapter treats in full. The data dictionary is where you catch it first.
Check the target's quality
The target column deserves more scrutiny than any feature. Check these points:
- Definition: Is the label recorded the way you defined it? "Cancelled" might include non-payment closures that you consider a different event.
- Timing: Was the label recorded at a consistent delay after the features? A label that matures late, such as a loan default after 12 months, means recent rows have no label yet.
- Noise: Are labels assigned by people who disagree? Sample a few dozen and check.
- Selection: Do you only see labels for cases that got an action? A credit model trained only on approved applicants never sees what happened to rejected ones.
Check that the sample matches the future
A model is trained on past data but applied to future data. It works only if the two are similar enough. Ask how the data was sampled. Data from one region, one season or one product version may not represent the cases you will score.
Time matters most. If the data spans several periods, plan to check whether the distributions change over time. A shift between training data and live data is called drift, covered in the monitoring chapter. You can often spot it early by comparing the first and last months of your history.
Inspect the data in code
Load the data and check its shape, types, missing values and duplicates before anything else. The example below builds a small table with typical problems so that you can run it as shown.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"customer_id": ["a1", "a2", "a3", "a3", "a4", "a5"],
"signup_date": ["2023-01-05", "2023-02-11", "2023-03-02",
"2023-03-02", "2023-13-40", "2023-05-20"],
"monthly_spend": [29.0, 45.5, np.nan, np.nan, 12.0, -3.0],
"plan": ["basic", "pro", "basic", "basic", "Pro", "basic"],
"cancelled": [0, 1, 0, 0, 1, 0],
})
print(df.shape)
print(df.dtypes)
print(df.isna().sum())
print("duplicate rows:", df.duplicated().sum())
print("duplicate ids:", df["customer_id"].duplicated().sum())
# Parse dates; invalid values become NaT instead of raising an error.
df["signup_date"] = pd.to_datetime(df["signup_date"], errors="coerce")
print("bad dates:", df["signup_date"].isna().sum())
print(df["plan"].value_counts())
print(df["monthly_spend"].describe())
print(df["cancelled"].value_counts(normalize=True))Running this reveals several issues that a quick glance would miss:
df.duplicated()finds one fully duplicated row (a3).monthly_spendhas two missing values and one negative value, which is probably an error or a refund.signup_datearrived as strings, and one value is not a real date.planholds"Pro"and"pro", which are the same category written two ways.value_counts(normalize=True)shows the class balance. Here two of six customers cancelled. In real data, a rare positive class affects the metric you choose later.
Do not fix these yet. Record them. Cleaning is the next stage but one, and it comes after exploration, so you decide with a full picture.
Common errors
- Assuming column meaning from its name.
incomemight be monthly, yearly, gross or net. Ask the owner or read the documentation. - Joining tables without checking the key. A join on a non-unique key multiplies rows silently. Compare the row count before and after, and assert uniqueness with
validate="one_to_one"or"many_to_one"inpd.merge. - Ignoring units and encodings. Mixed currencies, mixed time zones, and sentinel values such as
-1or9999for "unknown" look like real numbers. - Trusting a dataset's size. One million rows from 1,000 customers carry the information of far fewer independent samples.
- Using data you may not be allowed to use. Check privacy rules, consent and licensing before you model. Remove direct identifiers that the model does not need.
A short checklist
If a check fails, go back and change the data you collect. Do not hope that modeling will compensate.
Exercise
A table has one row per customer-month and the target is "cancelled next month". Name two problems you should check for at this stage, and say why each matters.
Show answer
First, repeated customers: the same customer appears in many rows, so the unit of analysis is the customer-month but the independent unit is the customer, and a random split would put one customer in both training and test. Second, features not known at prediction time: any column recorded after the outcome, such as a cancellation reason, would inflate test results but be unavailable when scoring real customers.
Exercise
In the code example, which line would you change if plan values "Pro" and "pro" should be treated as one category, and why should you wait to apply that change until after exploration?
Show answer
You would normalize the text, for example df["plan"] = df["plan"].str.lower(). Waiting lets you first see all the issues together, such as other spelling variants, so you choose one consistent cleaning rule with the full picture instead of patching problems one at a time.