10 Data Sanity Checks to Keep Your Sanity
Table of Contents
In this post we will cover some common data sanity checks that can help maintain your own sanity when working with data. This is a step that really comes before typical exploratory data analysis: before you spend time trying to understand the actual patterns in your data, you want to limit the risk that what you see as patterns is caused by an error in bringing the data together.
As a working example, we will start with a table of customers, a table of segments those customers belong to, and, a table of events matching activities our customers carry out. From this we want to build a dataset of customer activity by day, which we could then use for many different downstream purposes.
We will do the required transformations in Python, using Polars. Depending on your actual situation, some of this might be done in SQL instead. We are doing it here in python because we want to showcase the power of using Python to explore the data and find problems. Once you have a really solid extract and transform step, run it in SQL if that is more performant.
We will take creating a table of customer activity from three base tables as a use case. After describing the tables we have and the table we want, we’ll go through the checks. For each check, we will first diagnose the problem, then address it, then make sure the problem won’t happen again with an assertion. Towards the end we will build the final table.
If you would like to play along at home, you can download the code that generates all the data from the data sanity checks resource pack.
The tables we have #
The code snippet below reads in the three tables and defines the date range.
from datetime import date
import matplotlib.pyplot as plt
import numpy as np
import polars as pl
from data import make_data
pl.Config.set_tbl_cols(-1)
pl.Config.set_tbl_width_chars(200)
customers, segments, events = make_data()
window_start, window_end = date(2025, 1, 1), date(2025, 12, 31)
First step is to just look at the tables.
customers.head()
shape: (5, 3)
┌─────────────┬─────────────┬──────────────┐
│ customer_id ┆ signup_date ┆ cancelled_at │
│ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ date │
╞═════════════╪═════════════╪══════════════╡
│ 1 ┆ 2025-07-27 ┆ null │
│ 2 ┆ 2025-06-05 ┆ null │
│ 3 ┆ 2025-05-05 ┆ 2025-09-20 │
│ 4 ┆ 2025-03-07 ┆ null │
│ 5 ┆ 2025-03-17 ┆ null │
└─────────────┴─────────────┴──────────────┘
We can see we have a customer_id along with a signup and cancel date. The next table is the segments table.
segments.head()
shape: (5, 4)
┌─────────────┬────────────────────┬──────┬────────────┐
│ customer_id ┆ industry ┆ size ┆ valid_from │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ date │
╞═════════════╪════════════════════╪══════╪════════════╡
│ 1 ┆ Health ┆ mid ┆ 2025-07-27 │
│ 2 ┆ Health ┆ mid ┆ 2025-06-05 │
│ 2 ┆ Financial Services ┆ mid ┆ 2025-12-11 │
│ 3 ┆ Fintech ┆ mid ┆ 2025-05-05 │
│ 3 ┆ Financial Services ┆ mid ┆ 2025-07-01 │
└─────────────┴────────────────────┴──────┴────────────┘
Segments have two dimensions, industry and size, and, it also looks like the structure is a little bit more complicated, with more than one row per customer, with a start date for when the segment applies.
Lastly, we have the events table:
events.head()
shape: (5, 6)
┌──────────┬─────────────┬───────────┬────────────────┬──────────────────────┬────────┐
│ event_id ┆ customer_id ┆ product ┆ action ┆ ts ┆ amount │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ str ┆ str ┆ f64 │
╞══════════╪═════════════╪═══════════╪════════════════╪══════════════════════╪════════╡
│ 22460 ┆ 89 ┆ Reports ┆ schedule ┆ 2025-11-22T10:11:16Z ┆ null │
│ 27304 ┆ 105 ┆ API ┆ call ┆ 2025-09-05T14:32:56Z ┆ null │
│ 31592 ┆ 124 ┆ Analytics ┆ view_dashboard ┆ 2025-10-25T14:58:16Z ┆ null │
│ 19306 ┆ 76 ┆ API ┆ call ┆ 2025-09-04T06:30:01Z ┆ null │
│ 24264 ┆ 94 ┆ API ┆ key_created ┆ 2025-02-25T13:58:01Z ┆ null │
└──────────┴─────────────┴───────────┴────────────────┴──────────────────────┴────────┘
This table has, it looks like, one row per event, with a customer_id and ts
(timestamp) but also a product and action. It looks like there might be some
metadata for some events.
The table we want #
From these tables we want to build up a basic dataset of customer activity across products and actions and over time. By including the segment information we can then also understand those dimensions across and within segments. It should look something like this.
target = pl.DataFrame(
schema={
"customer_id": pl.Int64,
"date": pl.Date,
"industry": pl.String,
"size": pl.String,
"n_events": pl.UInt32,
"n_products": pl.UInt32,
"amount": pl.Float64,
"missing_amount": pl.UInt32,
"logging_gap": pl.Boolean,
}
)
target
shape: (0, 9)
┌─────────────┬──────┬──────────┬──────┬──────────┬────────────┬────────┬────────────────┬─────────────┐
│ customer_id ┆ date ┆ industry ┆ size ┆ n_events ┆ n_products ┆ amount ┆ missing_amount ┆ logging_gap │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ str ┆ str ┆ u32 ┆ u32 ┆ f64 ┆ u32 ┆ bool │
╞═════════════╪══════╪══════════╪══════╪══════════╪════════════╪════════╪════════════════╪═════════════╡
└─────────────┴──────┴──────────┴──────┴──────────┴────────────┴────────┴────────────────┴─────────────┘
1. No duplicate rows #
It hardly ever makes sense to have rows of a table that are exactly the same, or duplicate, so we want to check for that. We can use list comprehensions to apply the same check to all our tables. If you have a lot of tables, or, a lot of operations you want to apply to all tables, you can put them in a dictionary, keyed by their name as a string, for convenience. For more on dictionaries, see the python basics post.
[t.is_duplicated().sum() for t in [customers, segments, events]]
[0, 0, 80]
The events table has duplicated rows, let’s look at them:
events.filter(events.is_duplicated()).sort("ts").head()
shape: (5, 6)
┌──────────┬─────────────┬───────────┬──────────┬───────────────────────────┬────────┐
│ event_id ┆ customer_id ┆ product ┆ action ┆ ts ┆ amount │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ str ┆ str ┆ f64 │
╞══════════╪═════════════╪═══════════╪══════════╪═══════════════════════════╪════════╡
│ 41335 ┆ 167 ┆ API ┆ call ┆ 2025-03-24T09:52:53-08:00 ┆ null │
│ 41335 ┆ 167 ┆ API ┆ call ┆ 2025-03-24T09:52:53-08:00 ┆ null │
│ 28458 ┆ 110 ┆ Analytics ┆ export ┆ 2025-04-15T17:20:23-05:00 ┆ null │
│ 28458 ┆ 110 ┆ Analytics ┆ export ┆ 2025-04-15T17:20:23-05:00 ┆ null │
│ 40439 ┆ 163 ┆ Billing ┆ purchase ┆ 2025-04-29T17:34:36+01:00 ┆ null │
└──────────┴─────────────┴───────────┴──────────┴───────────────────────────┴────────┘
When you find duplicated data, always let the producer know, so that they can fix the root cause and improve data quality. For now, in this context, we will just filter them out.
events = events.unique(maintain_order=True)
We also use an assertion to make sure there are no duplicated rows in any of our tables:
assert all([t.is_duplicated().sum() == 0 for t in [customers, segments, events]])
2. Know the grain of each table #
Before using a table, we should know its structure: what units
do it hold, and, how do those units relate to the rows? Put differently, what
is the grain of the table? Does it have one row per customer, or something
more complicated? This is especially important when using a table in joins.
To check, we can count the number of rows per key value, and show a few rows
for the key value with the most rows. That will give us a good sense of the
structure of the table. We implement this in the function busiest_key, so
we can use it repeatedly. For more on functions, see the python basics
post.
def busiest_key(df, *key):
top = (
# one group per key value, in the order they first appear
df.group_by(*key, maintain_order=True)
# count the rows in each group (in a column called "len")
.len()
# most rows first; ties keep their order, so the result is the same every run
.sort("len", descending=True, maintain_order=True)
# take the first one, the busiest key value, as a dictionary
.row(0, named=True)
)
# all the rows of the table that have that key value
rows = df.filter(*(pl.col(k) == top[k] for k in key))
# add how many rows there are for the key, and show at most 10
return rows.with_columns(rows_for_key=top["len"]).head(10)
busiest_key(customers, "customer_id")
shape: (1, 4)
┌─────────────┬─────────────┬──────────────┬──────────────┐
│ customer_id ┆ signup_date ┆ cancelled_at ┆ rows_for_key │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ date ┆ i32 │
╞═════════════╪═════════════╪══════════════╪══════════════╡
│ 1 ┆ 2025-07-27 ┆ null ┆ 1 │
└─────────────┴─────────────┴──────────────┴──────────────┘
In this case, there are no ids that have anything but one row, so that is good.
busiest_key(segments, "customer_id")
shape: (3, 5)
┌─────────────┬────────────────────┬───────┬────────────┬──────────────┐
│ customer_id ┆ industry ┆ size ┆ valid_from ┆ rows_for_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ date ┆ i32 │
╞═════════════╪════════════════════╪═══════╪════════════╪══════════════╡
│ 42 ┆ Fintech ┆ small ┆ 2025-01-07 ┆ 3 │
│ 42 ┆ Software ┆ small ┆ 2025-08-12 ┆ 3 │
│ 42 ┆ Financial Services ┆ small ┆ 2025-07-01 ┆ 3 │
└─────────────┴────────────────────┴───────┴────────────┴──────────────┘
For segments, we already saw that there are multiple rows for at least some
key values. Here we can see that the same customer can be in different
industries at different times.
busiest_key(segments, "customer_id", "valid_from")
shape: (1, 5)
┌─────────────┬──────────┬──────┬────────────┬──────────────┐
│ customer_id ┆ industry ┆ size ┆ valid_from ┆ rows_for_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ date ┆ i32 │
╞═════════════╪══════════╪══════╪════════════╪══════════════╡
│ 1 ┆ Health ┆ mid ┆ 2025-07-27 ┆ 1 │
└─────────────┴──────────┴──────┴────────────┴──────────────┘
Once we add valid_from as another key, we see that it together with
customer_id uniquely identifies a row.
For events, we can see that one customer can have multiple events.
busiest_key(events, "customer_id")
shape: (10, 7)
┌──────────┬─────────────┬─────────┬───────────────┬───────────────────────────┬────────┬──────────────┐
│ event_id ┆ customer_id ┆ product ┆ action ┆ ts ┆ amount ┆ rows_for_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ str ┆ str ┆ f64 ┆ i32 │
╞══════════╪═════════════╪═════════╪═══════════════╪═══════════════════════════╪════════╪══════════════╡
│ 2507 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-07-17T12:52:42+01:00 ┆ null ┆ 726 │
│ 2737 ┆ 9 ┆ Reports ┆ create_report ┆ 2025-11-04T09:41:21+01:00 ┆ null ┆ 726 │
│ 2657 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-10-01T09:43:16+01:00 ┆ null ┆ 726 │
│ 2824 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-12-08T06:02:09+01:00 ┆ null ┆ 726 │
│ 2839 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-12-16T15:26:33+01:00 ┆ null ┆ 726 │
│ 2528 ┆ 9 ┆ Billing ┆ purchase ┆ 2025-07-28T10:50:43+01:00 ┆ 68.14 ┆ 726 │
│ 2365 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-05-20T16:42:41+01:00 ┆ null ┆ 726 │
│ 2558 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-08-09T10:43:18+01:00 ┆ null ┆ 726 │
│ 2296 ┆ 9 ┆ Reports ┆ schedule ┆ 2025-04-25T11:00:33+01:00 ┆ null ┆ 726 │
│ 2831 ┆ 9 ┆ Reports ┆ create_report ┆ 2025-12-13T11:20:44+01:00 ┆ null ┆ 726 │
└──────────┴─────────────┴─────────┴───────────────┴───────────────────────────┴────────┴──────────────┘
As expected, the event_id column now uniquely identifies a row.
busiest_key(events, "event_id")
shape: (1, 7)
┌──────────┬─────────────┬─────────┬──────────┬──────────────────────┬────────┬──────────────┐
│ event_id ┆ customer_id ┆ product ┆ action ┆ ts ┆ amount ┆ rows_for_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ str ┆ str ┆ f64 ┆ i32 │
╞══════════╪═════════════╪═════════╪══════════╪══════════════════════╪════════╪══════════════╡
│ 22460 ┆ 89 ┆ Reports ┆ schedule ┆ 2025-11-22T10:11:16Z ┆ null ┆ 1 │
└──────────┴─────────────┴─────────┴──────────┴──────────────────────┴────────┴──────────────┘
Get the Checks
Get the 10 sanity checks as Python code, as AI instructions, and as a PDF cheatsheet, plus the code that generates the data in this post. We won't send you spam. Unsubscribe at any time.
3. Foreign Key Check: Every event has a customer #
To make our table of activity with customer attributes, we will need to join in customer attributes into the events table. Before doing that, we want to make sure that all events have customer data.
This is a so-called foreign key check. We can accomplish it with an
anti-join, which results in the rows from the event table without
corresponding customer table rows, when joining on customer_id
[t.join(customers, on="customer_id", how="anti").height for t in [segments, events]]
[0, 25]
orphans = events.join(customers, on="customer_id", how="anti")
orphans.height, orphans["customer_id"].unique().to_list()
(25, [9001, 9002, 9003])
Always notify the producer of the data if you find orphan rows, so that they can address it upstream and improve data quality over time. Here, we are just going to filter them out. We can use a “semi join” to filter out the orphan rows. A semi join keeps the rows in the left table that have a match in the right table. For more on joins, see the SQL post.
segments = segments.join(customers, on="customer_id", how="semi")
events = events.join(customers, on="customer_id", how="semi")
Once we have filtered out the orphan rows, we check that there are none left with an assertion.
assert all([t.join(customers, on="customer_id", how="anti").is_empty() for t in [segments, events]])
4. Joins do not change the row count #
Another danger when doing joins is that the number of rows changes in unexpected ways. To guard against this, record the number of rows you want the final table to have, then check it after the join. In this case, we want to join segment information into the events table, without changing the events count.
n_events = events.height
naive = events.join(segments, on="customer_id")
naive.height, n_events
(68715, 50005)
The number of rows increased, because a customer can have multiple segments (over time) as we saw above, so asserting that the number of rows is the same will throw an error:
assert naive.height == n_events, f"{naive.height} rows, expected {n_events}"
AssertionError: 68715 rows, expected 50005
polars has a built-in validate argument, in this case we want to check that
many events map to one segment row, i.e. that the join is many-to-one, or "m:1". It raises an error here, because segments has several rows for the same customer_id, so the join is many-to-many.
events.join(segments, on="customer_id", validate="m:1")
ComputeError: join keys did not fulfill m:1 validation
5. Timestamps and time zones #
If you have data from more than one time zone, you have to take this into account. If you want to understand the underlying process in its context, then, you have to use the timezone local to the event. One example of this would be daily seasonal patterns, which are related to the rhythm of for example waking or working hours in that locale.
If you need to relate your data to events that occur at specific times, for example if you are understanding a rollout or incident, coordinated universal time (UTC) is easier to deal with.
events = events.with_columns(
# the first 19 characters are the date and time as written (the customer's
# local time), without the offset
local_ts=pl.col("ts").str.slice(0, 19).str.to_datetime(),
# the whole string including the offset, converted to UTC
ts=pl.col("ts").str.to_datetime("%Y-%m-%dT%H:%M:%S%#z", time_zone="UTC"),
)
The figure below illustrates how what shows up as a clear pattern in local time, becomes much more diffuse when viewed in UTC.
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
axes[0].hist(events["ts"].dt.hour(), bins=range(25))
axes[0].set_title("hour of day, UTC")
axes[1].hist(events["local_ts"].dt.hour(), bins=range(25))
axes[1].set_title("hour of day, local");

events = events.with_columns(date=pl.col("local_ts").dt.date())
Get the Checks
Get the 10 sanity checks as Python code, as AI instructions, and as a PDF cheatsheet, plus the code that generates the data in this post. We won't send you spam. Unsubscribe at any time.
6. Events fall within the customer lifetime #
If you have multiple sources of information on one of your units, like we have customer activity and their start and end date, you can use one to sanity check the other, so that customer activity always falls between their start and end date. In many real applications this can be trickier because customers may have free and extended trials, or might re-negotiate contracts or get extensions, etc. It’s still always worth sanity checking event timestamps, almost without fail there will be some that are either unbelievably early or late. These are likely missing data filled in with a default, or, parsing errors.
In this example we plot activity, along with supposed start and end times.
def plot_activity(events, customers):
"""One row per customer, one column per week; dark = any events that week."""
monday = date(2024, 12, 30)
rows = (
customers.sort("signup_date")
.with_row_index("row")
.with_columns(
signup_week=(pl.col("signup_date") - monday).dt.total_days() // 7,
cancel_week=(pl.col("cancelled_at") - monday).dt.total_days() // 7,
)
)
cells = (
events.with_columns(week=(pl.col("date") - monday).dt.total_days() // 7)
.select("customer_id", "week")
.unique()
.join(rows.select("customer_id", "row"), on="customer_id")
)
grid = np.zeros((rows.height, 53))
grid[cells["row"].to_numpy(), cells["week"].to_numpy()] = 1
fig, ax = plt.subplots(figsize=(8, 6))
ax.imshow(grid, aspect="auto", cmap="Greys", interpolation="nearest")
s, c = rows.drop_nulls("signup_week"), rows.drop_nulls("cancel_week")
ax.scatter(s["signup_week"], s["row"], marker="|", color="tab:green", s=12)
ax.scatter(c["cancel_week"], c["row"], marker="|", color="tab:red", s=12)
ax.set_xlabel("week")
ax.set_ylabel("customer (by signup)")
plot_activity(events, customers);

Squinting at the plot, we can see some instances of customers that cancelled before signing up, which seems illogical.
customers.filter(pl.col("cancelled_at") < pl.col("signup_date"))
shape: (3, 3)
┌─────────────┬─────────────┬──────────────┐
│ customer_id ┆ signup_date ┆ cancelled_at │
│ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ date │
╞═════════════╪═════════════╪══════════════╡
│ 26 ┆ 2025-07-29 ┆ 2025-07-19 │
│ 167 ┆ 2025-02-26 ┆ 2025-02-16 │
│ 170 ┆ 2025-04-12 ┆ 2025-04-02 │
└─────────────┴─────────────┴──────────────┘
If you see this, make sure to ask the producer of the data, it could be a bug or an actual behavior that you are only partially understanding. For our purposes here, we set those customers’ cancel date to null.
customers = customers.with_columns(
cancelled_at=pl.when(pl.col("cancelled_at") >= pl.col("signup_date"))
.then(pl.col("cancelled_at"))
.otherwise(None)
)
assert not (customers["cancelled_at"] < customers["signup_date"]).any()
In the plot, we also see some events that happen before the signup date.
To get a handle on the exact events, we have to join in the customer start and end dates.
events = events.join(customers, on="customer_id", validate="m:1")
before = events.filter(pl.col("date") < pl.col("signup_date"))
after = events.filter(pl.col("date") > pl.col("cancelled_at"))
before.height, after.height
(30, 40)
before.group_by("customer_id").agg(
n_events=pl.len(),
earliest=pl.col("date").min(),
signup_date=pl.col("signup_date").first(),
).sort("earliest").head()
shape: (5, 4)
┌─────────────┬──────────┬────────────┬─────────────┐
│ customer_id ┆ n_events ┆ earliest ┆ signup_date │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ u32 ┆ date ┆ date │
╞═════════════╪══════════╪════════════╪═════════════╡
│ 35 ┆ 1 ┆ 2024-12-17 ┆ 2025-01-06 │
│ 97 ┆ 1 ┆ 2024-12-24 ┆ 2025-01-12 │
│ 28 ┆ 1 ┆ 2024-12-24 ┆ 2025-01-09 │
│ 137 ┆ 1 ┆ 2024-12-29 ┆ 2025-01-12 │
│ 108 ┆ 1 ┆ 2025-01-14 ┆ 2025-01-15 │
└─────────────┴──────────┴────────────┴─────────────┘
We can then filter out the events that happen before the start date and after the end date. In a real application, only do this once you fully understand how the data is generated and can make an informed decision.
events = events.filter(
(pl.col("date") >= pl.col("signup_date"))
& (pl.col("cancelled_at").is_null() | (pl.col("date") <= pl.col("cancelled_at")))
)
assert (events["date"] >= events["signup_date"]).all()
assert (events["cancelled_at"].is_null() | (events["date"] <= events["cancelled_at"])).all()
plot_activity(events, customers);

Get the Checks
Get the 10 sanity checks as Python code, as AI instructions, and as a PDF cheatsheet, plus the code that generates the data in this post. We won't send you spam. Unsubscribe at any time.
7. Consistent naming and spelling #
Very often you’ll find that named categories such as products or segments have inconsistent spellings and case. The problem is of course that while a human can see that a word is the same regardless of whether it’s upper or lowercase, it will look like two different strings to most machines.
events["product"].value_counts().sort("product")
shape: (8, 2)
┌───────────┬───────┐
│ product ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════════╪═══════╡
│ API ┆ 14180 │
│ Analytics ┆ 14023 │
│ Billing ┆ 4831 │
│ Reports ┆ 15450 │
│ analytics ┆ 448 │
│ api ┆ 414 │
│ billing ┆ 151 │
│ reports ┆ 438 │
└───────────┴───────┘
We will just standardize them here, but in real applications I recommend telling the producer of the data so they can fix it at the source, and, hopefully also prevent the same issue in the future.
events = events.with_columns(
product=pl.col("product").str.to_titlecase().replace({"Api": "API"})
)
In this case we test against a specific, hard-coded set of products. Depending on your application you may or may not want this check.
assert set(events["product"].unique()) == {"Analytics", "Reports", "API", "Billing"}
events["product"].value_counts().sort("product")
shape: (4, 2)
┌───────────┬───────┐
│ product ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════════╪═══════╡
│ API ┆ 14594 │
│ Analytics ┆ 14471 │
│ Billing ┆ 4982 │
│ Reports ┆ 15888 │
└───────────┴───────┘
A more subtle problem is that values are renamed over time. Sometimes, the rename is just cosmetic but sometimes it comes with substantive changes to the system as well. Here is an example, with “Fintech” being replaced by “Financial Services”.
segments.group_by("industry").agg(
rows=pl.len(),
first_valid_from=pl.col("valid_from").min(),
last_valid_from=pl.col("valid_from").max(),
).sort("first_valid_from")
shape: (5, 4)
┌────────────────────┬──────┬──────────────────┬─────────────────┐
│ industry ┆ rows ┆ first_valid_from ┆ last_valid_from │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ date ┆ date │
╞════════════════════╪══════╪══════════════════╪═════════════════╡
│ Health ┆ 71 ┆ 2025-01-01 ┆ 2025-11-28 │
│ Software ┆ 70 ┆ 2025-01-03 ┆ 2025-12-24 │
│ Fintech ┆ 35 ┆ 2025-01-04 ┆ 2025-06-29 │
│ Retail ┆ 51 ┆ 2025-01-06 ┆ 2025-11-29 │
│ Financial Services ┆ 40 ┆ 2025-07-01 ┆ 2025-12-11 │
└────────────────────┴──────┴──────────────────┴─────────────────┘
Here we just standardize the naming, but, I recommend that you only do this once you fully understand why the renaming was done so that you can make a deliberate decision.
rename = {"Fintech": "Financial Services"}
segments = segments.with_columns(industry=pl.col("industry").replace(rename))
assert (segments["industry"] != "Fintech").all()
8. Nulls you expect and nulls you do not #
It’s always very useful to check what proportion of values in a column are null. If you do find nulls, make sure to check if they are to be expected or not.
(events.null_count() / events.height).unpivot(
variable_name="column", value_name="null_share"
).sort("null_share", descending=True)
shape: (10, 2)
┌──────────────┬────────────┐
│ column ┆ null_share │
│ --- ┆ --- │
│ str ┆ f64 │
╞══════════════╪════════════╡
│ amount ┆ 0.905197 │
│ cancelled_at ┆ 0.848904 │
│ event_id ┆ 0.0 │
│ customer_id ┆ 0.0 │
│ product ┆ 0.0 │
│ action ┆ 0.0 │
│ ts ┆ 0.0 │
│ local_ts ┆ 0.0 │
│ date ┆ 0.0 │
│ signup_date ┆ 0.0 │
└──────────────┴────────────┘
In our case, cancelled_at values being null is to be expected, those are customers who haven’t cancelled (it also includes those customers with bad cancellation dates that we set to null).
To understand the nulls in the amount column, we break it down by the action column:
share = (
events.group_by("action")
.agg(null_share=pl.col("amount").is_null().mean())
.sort("null_share")
)
fig, ax = plt.subplots(figsize=(8, 3.5))
ax.barh(share["action"], share["null_share"])
ax.set_xlabel("share of events with no amount");

In our data, only some events are purchases, and, only purchase events carry
an amount. So we expect null amounts for action values other than purchase.
Conversely, we don’t expect any null amounts for purchase events, but the
plot shows that a few percent are in fact null. The code below shows the exact number that have missing data, out of the total.
# Only purchases carry an amount, so a null there is a bug; elsewhere it is normal.
assert events.filter(pl.col("action") != "purchase")["amount"].is_null().all()
purchase_without_amount = (pl.col("action") == "purchase") & pl.col("amount").is_null()
n_missing = events.filter(purchase_without_amount).height
n_missing, events.filter(pl.col("action") == "purchase").height
(248, 4982)
9. No missing days #
Never rely on a table having rows on all dates to create a complete time series. Always create a spine of all the dates in a time range, then, join your data into that spine. That way, you will easily be able to see if you have dates without data. In the plot below we see a period of such dates clearly. Once you see them, you can then make a deliberate decision about how to handle those dates. Always ask or notify the upstream producer of the data. If you are working with a time series, you may want to impute those dates. If you are not using the time aspect, or have freedom in what time periods to choose, you can avoid that time period altogether.
all_days = pl.DataFrame({"date": pl.date_range(window_start, window_end, eager=True)})
per_day = all_days.join(
events.group_by("date").agg(n=pl.len()), on="date", how="left"
).with_columns(pl.col("n").fill_null(0))
fig, ax = plt.subplots(figsize=(8, 3.5))
ax.plot(per_day["date"], per_day["n"])
ax.set_ylabel("events per day");

Get the Checks
Get the 10 sanity checks as Python code, as AI instructions, and as a PDF cheatsheet, plus the code that generates the data in this post. We won't send you spam. Unsubscribe at any time.
Making the join #
With the preceding checks, we are ready to do the final join. The first step is to create a grid of customer-dates, so that we have one row for each day in a customer’s tenure.
life = customers.with_columns(
end=pl.min_horizontal(pl.col("cancelled_at"), pl.lit(window_end))
)
grid = life.select(
"customer_id", date=pl.date_ranges("signup_date", "end")
).explode("date")
grid.head()
shape: (5, 2)
┌─────────────┬────────────┐
│ customer_id ┆ date │
│ --- ┆ --- │
│ i64 ┆ date │
╞═════════════╪════════════╡
│ 1 ┆ 2025-07-27 │
│ 1 ┆ 2025-07-28 │
│ 1 ┆ 2025-07-29 │
│ 1 ┆ 2025-07-30 │
│ 1 ┆ 2025-07-31 │
└─────────────┴────────────┘
We then aggregate the events up to the daily level, keeping track of how many purchase events lack an amount.
daily = events.group_by("customer_id", "date").agg(
n_events=pl.len(),
n_products=pl.col("product").n_unique(),
amount=pl.col("amount").sum(),
missing_amount=((pl.col("action") == "purchase") & pl.col("amount").is_null()).sum(),
)
We then create the final activity table by first, taking the grid of
customer-dates and joining in the daily event data. We then calculate the
logging_gap, if a day has no events across all customers. Then we join in
the customer segment information, using an “as-of” join (join_asof), where
the customer_id has to match, and, where we take the row from the right table
where the latest valid_from date is on or before the date from the left table.
For this join to work properly, the inputs have to be sorted. Once we have
done all the joins, we select the final columns we want and sort.
activity = (
# Join daily event data into customer-date grid.
grid.join(daily, on=["customer_id", "date"], how="left")
# Fill nulls (when there is no event data) with zeros.
.with_columns(
pl.col("n_events", "n_products", "missing_amount").fill_null(0),
pl.col("amount").fill_null(0.0),
)
# Record dates with no event data.
.with_columns(
logging_gap=(pl.col("n_events").sum().over("date") == 0)
& (pl.col("date") > pl.col("date").filter(pl.col("n_events") > 0).min())
)
# Sort by date.
.sort("date")
# Join on customer_id and latest valid_from on or before date.
.join_asof(
segments.sort("valid_from"),
left_on="date",
right_on="valid_from",
by="customer_id",
)
# Select final columns.
.select(
"customer_id",
"date",
"industry",
"size",
"n_events",
"n_products",
"amount",
"missing_amount",
"logging_gap",
)
# Sort.
.sort("customer_id", "date")
)
If you run this yourself, you will see a warning from join_asof: polars
cannot check that the data is sorted when the join uses by groups, so it is
up to us to sort both tables by their date columns first, which is why the
code calls .sort() on each.
This is what the final table looks like.
activity.head()
shape: (5, 9)
┌─────────────┬────────────┬──────────┬──────┬──────────┬────────────┬────────┬────────────────┬─────────────┐
│ customer_id ┆ date ┆ industry ┆ size ┆ n_events ┆ n_products ┆ amount ┆ missing_amount ┆ logging_gap │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ str ┆ str ┆ u32 ┆ u32 ┆ f64 ┆ u32 ┆ bool │
╞═════════════╪════════════╪══════════╪══════╪══════════╪════════════╪════════╪════════════════╪═════════════╡
│ 1 ┆ 2025-07-27 ┆ Health ┆ mid ┆ 0 ┆ 0 ┆ 0.0 ┆ 0 ┆ false │
│ 1 ┆ 2025-07-28 ┆ Health ┆ mid ┆ 0 ┆ 0 ┆ 0.0 ┆ 0 ┆ false │
│ 1 ┆ 2025-07-29 ┆ Health ┆ mid ┆ 3 ┆ 2 ┆ 0.0 ┆ 0 ┆ false │
│ 1 ┆ 2025-07-30 ┆ Health ┆ mid ┆ 0 ┆ 0 ┆ 0.0 ┆ 0 ┆ false │
│ 1 ┆ 2025-07-31 ┆ Health ┆ mid ┆ 6 ┆ 3 ┆ 0.0 ┆ 0 ┆ false │
└─────────────┴────────────┴──────────┴──────┴──────────┴────────────┴────────┴────────────────┴─────────────┘
10. The final table matches the inputs #
Finally, when we’ve created the table we want, we also run the checks that apply to the final table structure once more, along with a few new ones, to make sure that everything is correct.
check = activity.join(customers, on="customer_id", validate="m:1")
assert not activity.select("customer_id", "date").is_duplicated().any()
assert (check["date"] >= check["signup_date"]).all()
assert (check["cancelled_at"].is_null() | (check["date"] <= check["cancelled_at"])).all()
assert activity["industry"].null_count() == 0
assert activity["n_events"].sum() == events.height
assert activity["missing_amount"].sum() == n_missing
assert activity.height == grid.height
assert activity.schema == target.schema
activity.shape
(40680, 9)
Conclusion #
Extracting, transforming and joining the data you need for your analysis or models has many opportunities for things to go wrong. The earlier you find a bug, the better, and so invest in checking your data before you go into the analysis or modeling. Writing checks as assertions ensures that you won’t see that specific bug again. Always pushing data quality issues upstream helps improve it over time.
If you want a head start on implementing these checks in your own work, check out the data sanity checks resource pack. It has the code to generate the data in this post, as well as the code for the checks, a cheatsheet PDF for easy reference, and, a markdown text file with instructions for coding agents to implement and use these checks.