Module 8 · Information Systems · Lesson 2 · Week 2

Advanced Exploratory Data Analysis

Reading material on the exploratory analysis of the partner data. It places the analysis in the information viewpoint and in the data lifecycle, prepares the environment with Poetry and Jupyter, develops an eight-step procedure with pandas and PySpark code, proposes a data quality log linked to the Data Model Canvas and shows how to store a first sample in the Data Lake as partitioned Parquet files.

About this session

Advanced Exploratory Data Analysis · 19/10/2026 · Prof. Afonso

Learning objective

By the end of the session, students should be able to conduct the eight-step exploratory analysis on the partner data with an AI assistant, sending it only the schema and aggregated outputs and reproducing in the notebook every finding it proposes, record the findings in a data quality log, use the log to fill the blocks of the Data Model Canvas, store a sample in the Data Lake with an idempotent Parquet write, and present the findings, their volume and the canvas blocks they change to the class.

Session strategy

Flipped session. Before class, each member prepares the environment, runs Steps 1 and 2 of the starter notebook on synthetic data and reads the material on the first steps. The session opens with an oral entry check and a focused exposition of Steps 3 to 8 and of the discovery loop with an AI assistant, in which the assistant writes the checks and interprets aggregated outputs while the group runs the code and decides. The groups then conduct Steps 3 to 8 on the partner data with the prompts of the session, record the findings in the data quality log, turn them into canvas entries and write a Parquet sample, and each group presents what it achieved to the class, which asks one question per group.

Session structure

  1. Daily — 15 min
  2. Entry check on the pre-class notebook — 5 min
  3. Focused exposition: steps 3 to 8 and the discovery loop with an AI assistant — 15 min
  4. Group practice on the partner data: AI-assisted steps 3 to 8, quality log, canvas and Parquet — 45 min
  5. Group presentations: what each group achieved — 30 min
  6. Sprint 1 deliverables and self-study — 10 min

1. How to read this material

This material accompanies the second session of Module 8, which follows a flipped format. Part of it is read before the session, so that the time in class is spent on the partner data, and the rest supports the group practice and the presentations.

Before the session, each member reads sections 2 to 8. Section 2 lists the pre-class tasks and the starter notebook. Sections 3 and 4 place the exploratory analysis in the information viewpoint of the RM-ODP and in the data lifecycle. Section 5 is the environment checklist, section 6 presents the eight-step procedure, and sections 7 and 8 develop Steps 1 to 4, of which the first two are executed in the starter notebook. During the session, sections 8 to 15 support the focused exposition of Steps 3 to 8 and the practice, including the data quality log and the Parquet write. Section 16 describes how the steps are conducted with an AI assistant and gives the prompts of the session, and sections 17 and 18 describe the group practice and the presentation of results.

The examples continue the fictitious pharmacy chain of Lesson 1, with the tables store, product, sale_line and stock_position. The starter notebook generates a synthetic version of these tables, and the figures that appear in the examples belong to that illustrative case and say nothing about the partner of the module. During the session each group replaces the table and column names with those of the partner dataset and keeps the order of the steps.

Before you start

Have the canvas of the group open in another tab and the starter notebook running inside the project environment. Sections 7 to 15 are written to be followed with a notebook open, one cell per step.

2. Before the session

The session is organised as a flipped classroom. The tasks that each member can complete alone, preparing the environment, running the first two steps and reading the procedure, are done before class, and the session is reserved for the work that benefits from the group and the professor, namely the analysis of the partner data and the discussion of its findings. A member who arrives without the environment working spends the group practice installing software, so the pre-class tasks are a condition for taking part in the session and not an optional preparation.

The tasks were announced at the end of Lesson 1 and are four. First, complete the environment checklist of section 5, which installs Python 3.12, checks Java 17 or later and prepares Poetry and Jupyter in the group repository. Second, download the starter notebook of the lesson and open it with poetry run jupyter notebook. Third, run the cell that generates the synthetic extract and the cells of Steps 1 and 2, and note what the inventory returns. Fourth, read sections 3 to 8 of this material, which cover the place of the analysis in the project and Steps 1 to 4.

Starter notebook

The notebook generates the synthetic pharmacy data with a fixed seed, so every member obtains the same figures, and it contains worked cells for Steps 1 and 2 and empty cells for Steps 3 to 8. Download lesson-2-starter.ipynb.

What to bring

The notebook executed up to Step 2, and the ability to explain what the inventory returned: the number of rows and its relation to stores, products and days, the type of the date column and the period covered.

The session opens with a short entry check, in which the professor asks a few questions about what Step 2 returned and what the grain test of Step 3 means. The answers are given orally, and they indicate which steps the focused exposition needs to explain in more detail.

3. Exploratory analysis and the information viewpoint

In Lesson 1 the group described the partner problem from two viewpoints of the RM-ODP. The enterprise viewpoint named the community, the decision at stake and the policies that constrain the use of data. The information viewpoint described the information objects that the decision needs, their relationships and the constraints over them, organised into invariant, static and dynamic schemas. That description was written before the data was read in depth, and it therefore contains assumptions that only the data can confirm.

The exploratory analysis is the procedure that tests those assumptions. Each invariant of the canvas becomes a query that counts violations, the declared grain becomes a test of uniqueness, and each relationship becomes a join whose losses are measured. The static schema is checked by looking at the state of the objects on a given date, for instance whether every store has a stock position every day. The dynamic schema is checked by following the life cycle of an object across time, for instance whether purchase orders move through the expected statuses. When a check fails, the group learns either that the data has an error or that its own description of the partner was wrong, and both outcomes are useful.

This lesson therefore closes the information viewpoint of Sprint 1. It also opens a new concern. Deciding where the sample of data is stored, under which naming convention and in which format is a decision about the mechanisms that hold the data, which belongs to the engineering viewpoint. The module develops that viewpoint in Sprints 4 and 5, but the first decisions are taken today, because every later layer of the pipeline will read from the structure created now.

Correspondence with the canvas

The findings of the analysis return to the canvas through the data quality log of section 12. Indicators that the data supports are confirmed in block 4, questions that need the partner go to block 6, checks that the pipeline must repeat go to block 14 and block j of the cube receives the correction rules.

4. The data lifecycle and the place of this lesson

Reis and Housley describe the data engineering lifecycle in five stages: generation, storage, ingestion, transformation and serving. Generation happens in the source systems, which in the illustrative case are the point-of-sale terminals and the stock control of the stores. Ingestion moves the data from those systems into the platform. Storage underlies every stage, because data is stored on arrival, after each transformation and before it is served. Transformation cleans, integrates and models the data, and serving delivers it to the people and systems that use it.

The two self-studies on lifecycles approach the same sequence from different angles. The reading on data lifecycle management emphasises the governance of each stage, from collection to deletion or archival. The reading on the analytics lifecycle emphasises the phases through which a question becomes an answer. Read together, they show that exploratory analysis sits between ingestion and transformation. It is the first moment in which the data received is examined, and its findings determine what the transformations must correct.

The consequence for the module is a clear division of work. This lesson receives a sample, explores it and stores it in a raw zone of the Data Lake. Lesson 3 organises the zones into the Bronze, Silver and Gold layers of the medallion architecture, and the lessons that follow implement the transformations, the data warehouse and the cubes. A finding recorded today, such as duplicated stock counts, becomes a rule of the Silver layer two weeks later.

SourceGenerationPoint of sale and stock control record events
PlatformIngestionExtracts arrive as files or tables
This lessonExplorationThe notebook checks the extract against the canvas
Lessons 3–6TransformationBronze, Silver, Gold, warehouse and cubes
Lessons 7–11ServingDataApp, dashboards and telemetry

Storage underlies every stage: data is stored on arrival, after each transformation and before it is served. Today the first sample is stored in the Data Lake as Parquet.

5. Preparing the environment with Poetry and Jupyter

An exploratory analysis is only useful if another person can run it and obtain the same results. Reproducibility depends on the exact versions of the libraries, because functions change behaviour between versions and a notebook that runs on one machine may fail or produce different numbers on another. Poetry addresses this problem by recording the dependencies of the project in pyproject.toml and the exact versions resolved for them in poetry.lock. When the lock file is committed, every member of the group installs the same versions with a single command.

The environment is prepared before the session, as a pre-class checklist, as part of the pre-class tasks of section 2, so that the time in class is spent on the partner data and not on installing software. One member adopts the group repository with poetry init and commits the two files. The option package-mode = false, added under [tool.poetry] in pyproject.toml, tells Poetry that the repository is a set of notebooks and scripts and not a library to be packaged, so it does not look for a package with the name of the project. The other members pull the repository and run poetry install. For a project that does not exist yet, poetry new <name> && cd <name> creates the standard layout instead.

Shell · pre-class checklist, adopting the group repository
poetry init --no-interaction --python ">=3.12,<3.13"
# then add, under [tool.poetry] in pyproject.toml:  package-mode = false
poetry env use python3.12
poetry add "pandas<3" pyarrow matplotlib pyspark jupyter
java -version                # PySpark 4 requires Java 17 or later
poetry run jupyter notebook

# teammates, after pulling pyproject.toml and poetry.lock
poetry install

Two constraints in these commands deserve an explanation. The Python version is pinned in requires-python because, without an upper bound, Poetry tries to resolve the dependencies for every future Python version and may refuse libraries that do not yet declare support for them. The pandas version is kept below 3 because PySpark 4 does not yet fully support pandas 3, and the Sprint 1 notebook uses both libraries in the same environment. Java is checked because PySpark starts a Java virtual machine, and PySpark 4 requires Java 17 or later. Since Poetry 2, the shell command is no longer part of the default installation, so commands are executed inside the environment through poetry run.

The notebooks are organised so that their structure mirrors the procedure. Each notebook covers one table or one analytical question, and its headings follow the eight steps of section 6. This organisation makes the notebook readable by the reviewer, who can find the evidence for each entry of the data quality log in the step with the same number.

Data outside the repository

Partner extracts must not be committed to a public repository. Keep them in a folder listed in .gitignore, such as data/, and commit only the notebooks, the lock file and the documentation.

6. The procedure in eight steps

Tukey introduced exploratory data analysis as a stage that precedes confirmatory analysis, in which the analyst looks at the data to discover what it can say before testing any hypothesis. In a data platform project the same idea takes a more procedural form. The group explores each table in a fixed order, because the conclusions of one step are premises of the next. Distributions computed before the grain is checked may count duplicated rows, and relationships computed before missing values are measured may reflect gaps in the extract rather than real behaviour.

The procedure below has eight steps. Each one answers a question about the table, computes a small number of measures and produces, when something relevant is found, an entry in the data quality log. The procedure is repeated for each table that supports an analytical question of the canvas.

StepQuestion it answersWhat is computed
1 · Start from the canvasWhich question and which grain does this table serve?A markdown cell with question, grain and invariants
2 · Load and inventoryHow large is the table, with which types, over which period?Shape, types, memory, minimum and maximum dates
3 · Structure and grainDoes the declared key identify each row?Duplicated keys and their inspection
4 · CompletenessWhere are values missing, and following which pattern?Null rates by column and by dimension
5 · Univariate profileHow is each column distributed?Summary statistics, cardinality, IQR outliers
6 · RelationshipsHow do variables move together and over time?Time series, cross-tabs, rank correlation
7 · Consistency across tablesDo joins and invariants hold?Orphan rows and invariant violations
8 · Record and decideWhat enters the log, and which canvas block changes?One log row per finding

The self-study on functional exploratory analysis organises a similar sequence into reusable Python functions. That organisation is worth adopting once the group has applied the steps to the first table, because the same checks will be repeated for every table and every new extract. Its cleaning functions belong to the Silver layer and are not applied during exploration.

In this session the steps are conducted with an AI assistant, which writes the code of each check and interprets its aggregated output. Section 16 describes the loop and the four prompts used in class. The order of the steps and the reference code of sections 7 to 15 remain the standard against which the code of the assistant is compared.

7. Steps 1 and 2: from the canvas to the inventory

The first step writes down why the table is being explored. A markdown cell at the top of the notebook records the analytical question from block 2 of the canvas, the grain declared for the table and the invariants that the group expects to hold. This cell has a practical function. It turns the notebook into a test of the canvas, and it allows the reviewer to judge each later cell by asking whether it contributes to the question stated at the top.

Markdown · first cell of the notebook
# Table: stock_position
# Question (block 2): which stores run out most often, and of which products?
# Declared grain: one row per product, store and day
# Invariants: on_hand >= 0; every (store_id, product_id) exists in store and product

The second step loads the table and takes its inventory. Dates are parsed at load time, so that the period covered can be computed from real date values and not from text. The shape gives the number of rows and columns, the types show whether numbers and dates were recognised, and the memory used indicates whether pandas on a single machine is sufficient or whether the analysis must move to Spark. The period covered is decisive, because an indicator computed over two weeks cannot support a decision that depends on seasonality.

pandas · load and inventory
import pandas as pd

sales = pd.read_csv("data/sale_line.csv", parse_dates=["sold_at"])
stock = pd.read_csv("data/stock_position.csv", parse_dates=["date"])

display(sales.shape)
display(sales.dtypes)
display(sales.memory_usage(deep=True).sum() / 1e6)   # megabytes
display(sales["sold_at"].agg(["min", "max"]))               # period covered

Jupyter shows only the value of the last expression of a cell. When a cell computes several results, as the inventory does, each one is wrapped in display, or the cell is split into one expression per cell, otherwise only the period covered would appear. The same convention is used in steps 5 and 7.

A column that should be numeric but appears with type object is the first finding of many analyses. It usually means that some values contain text, such as a decimal comma or a placeholder like "N/A", and the offending values are listed before any conversion is attempted.

8. Steps 3 and 4: grain and completeness

The grain is tested before any distribution is computed, because a duplicated row inflates every count and every sum that follows. The test is simple. The columns that the canvas declares as the key of the table are used to look for repeated combinations, and the repeated rows are displayed side by side. Two situations are common. In the first, the rows are identical, which indicates a duplicated extract or a record sent twice by the source system. In the second, the rows differ in some column, which indicates that the real grain is finer than the declared one, for instance because the stock is counted twice a day.

pandas · test of the declared grain
key = ["store_id", "product_id", "date"]

stock.duplicated(subset=key).sum()                     # rows beyond the first
dups = stock[stock.duplicated(subset=key, keep=False)]
dups.sort_values(key).head(20)                          # inspect side by side

Completeness is measured next. The null rate of each column is the starting point, but a single rate hides the pattern of the missing values, which is what explains them. Missing values concentrated in one store, one supplier or one period usually indicate a failure in the process that produced the data. Missing values spread uniformly are more often a property of the field, such as an optional attribute. The distinction matters, because the first case is reported to the partner and the second may be handled in the transformation layer.

pandas · null rates and their pattern
stock.isna().mean().sort_values(ascending=False)

(stock.groupby("store_id")["on_hand"]
      .apply(lambda s: s.isna().mean())
      .sort_values(ascending=False))

(stock.groupby(stock["date"].dt.to_period("W"))["on_hand"]
      .apply(lambda s: s.isna().mean()))

Missing values are not imputed during the exploration. Filling them with a mean or a zero at this stage would hide the finding from the partner and would introduce, without record, a decision that belongs to the transformation rules.

9. Step 5: the univariate profile

The univariate profile describes each column on its own. For numeric columns it consists of summary statistics, a histogram and a rule for outliers. For categorical columns it consists of the cardinality, that is, the number of distinct values, and the frequency of the most common values. The profile answers practical questions. It shows whether quantities are plausible, whether a category has too many values to be a useful dimension and whether a supposed code is in fact an identifier.

The rule most used for outliers is the one proposed by Tukey, based on the interquartile range. The first and third quartiles delimit the central half of the data, and the interquartile range is their difference. Values below the first quartile minus 1.5 times that range, or above the third quartile plus 1.5 times it, are marked as outliers. The rule is robust, because quartiles are not distorted by the extreme values that the rule seeks to find, which is what happens with the mean and the standard deviation.

pandas · summary, cardinality and IQR outliers
display(sales["quantity"].describe())
display(sales.nunique().sort_values())
display(sales["store_id"].value_counts().head(10))

q1, q3 = sales["quantity"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = sales[(sales.quantity < low) | (sales.quantity > high)]
display(len(outliers) / len(sales))

sales["quantity"].plot.hist(bins=50)

An outlier is a finding, and it is not deleted. A sale of four hundred units in a pharmacy may be a typing error or a legitimate order from a clinic, and only the partner can tell which. The group records the volume of outliers, examples of them and the question to be put to the partner. Sales data is also typically skewed, with many small values and few large ones, so the histogram is often more informative on a logarithmic scale.

10. Step 6: relationships between variables

Relationships are examined in three forms, each of which answers a different part of the analytical question. Relationships over time reveal seasonality, changes of level and gaps in the extract. Relationships between categories show how a measure varies across stores, products or regions. Relationships between numeric measures show which quantities move together. A chart produced in this step is kept in the notebook only if it supports a sentence in the data quality log or in the canvas, which prevents the notebook from becoming a gallery without conclusions.

pandas · time, categories and measures
# Over time: daily totals, which expose gaps and seasonality
daily = sales.groupby(sales.sold_at.dt.date)["quantity"].sum()
daily.plot()

# Between categories: share of stock-out days per store (first draft of the KPI)
obs = (stock.dropna(subset=["on_hand"])
            .drop_duplicates(["store_id", "product_id", "date"], keep="last"))
obs["on_hand"].le(0).groupby(obs["store_id"]).mean()

# Between measures: rank correlation on the measures only, never on identifiers
daily_sp = (sales.assign(date=sales["sold_at"].dt.normalize())
                 .groupby(["store_id", "product_id", "date"], as_index=False)["quantity"].sum()
                 .merge(obs, on=["store_id", "product_id", "date"]))
daily_sp[["quantity", "on_hand"]].corr(method="spearman")

The share of stock-out days by store deserves attention, because it is the first computation of the indicator defined in block 4 of the canvas. Rows without a stock count are removed and repeated counts keep the last record, so that days without a record leave the denominator and duplicates do not count twice, while a negative stock counts as a stock-out. The full KPI of Lesson 1 also keeps only continuous-use products and groups by week and product, as in its SQL query. If the share of stock-out days is close to zero in every store, the indicator may be poorly defined or the extract may not record stock-outs at all. Either conclusion changes the canvas before the pipeline is built around an indicator that the data cannot support.

Spearman correlation is preferred to Pearson correlation in this step because it uses the ranks of the values and not the values themselves. It therefore tolerates skewed distributions and outliers, which are common in sales and stock data. The measures are selected by name, because a matrix computed over every numeric column would correlate identifiers such as store_id, whose numbers carry no quantity. A correlation is a description and does not establish a cause, so it is recorded as a hypothesis to be discussed with the partner.

11. Step 7: consistency across tables

The relationships and invariants of the information viewpoint involve more than one table, and they are tested in this step. A relationship is tested with a join that marks the rows without a match. The share of unmatched rows decides whether the join can be used as it is, or whether the Silver layer must treat those rows before any indicator is built on the joined data. Measuring this share before using the join is essential, because an inner join silently discards unmatched rows and every indicator computed afterwards inherits the loss.

pandas · orphan rows and invariant violations
products = pd.read_csv("data/product.csv")

m = sales.merge(products, on="product_id", how="left", indicator=True)
display((m["_merge"] == "left_only").mean())          # share of orphan sale lines

display((stock["on_hand"] < 0).sum())                       # invariant on_hand >= 0
display((sales["quantity"] <= 0).sum())                    # returns or errors?
display((sales["sold_at"] > pd.Timestamp.now()).sum())       # dates in the future

Each invariant of the canvas becomes one line of code that counts violations. The log records the number of violations, because the decision depends on their volume. Three negative stock positions in two million rows may be handled by a rule in the Silver layer, whereas thousands of them indicate that the field has a meaning different from the one the group assumed.

The dynamic schema is checked in the same step when the dataset contains objects with a life cycle. For purchase orders, the group checks whether the statuses follow the expected order and whether the dates of each transition are consistent, for instance whether no order is received before it is approved.

12. Step 8: the data quality log

The last step turns the findings into a record that outlives the notebook. The data quality log is a table with one row per finding, kept in the repository next to the canvas. It states which table and which check produced the finding, its volume, its probable cause, the decision taken and the canvas block that the finding changes. The log is what the reviewer reads to understand the state of the data, and it is the source of the quality checks that the pipeline will run in later sprints.

IDTableCheckFinding and volumeProbable causeDecisionCanvas block
DQ-01stock_positionGrain1.8% of keys repeatStore count sent twiceRecord the volume; the treatment in Silver is decided in Lesson 314 · cube j
DQ-02stock_positionCompletenessOn-hand missing in two storesStores without a daily countAsk the partner6
DQ-03sale_lineOrphans0.4% of lines without productProduct table extracted earlierQuarantine the lines14
DQ-04sale_lineOutliers31 lines above 200 unitsPossible orders from clinicsValidate with the partner4 · 6

The figures in the table belong to the illustrative case, and what they illustrate is the structure of each entry. Every row links a fact observed in the data to a decision and to a place in the canvas, which keeps the correspondence between the information viewpoint and the data visible. A finding without a decision is an open question, and it goes to block 6 with an owner, as Lesson 1 recommended.

The template below can be copied into the repository and filled during the practice of the session, one row per finding.

Markdown · data quality log template
| ID | Table | Check | Finding and volume | Probable cause | Decision | Canvas block |
|----|-------|-------|--------------------|----------------|----------|--------------|
| DQ-01 |  |  |  |  |  |  |
Where to keep the log

A Markdown table under /docs/data_model_canvas/, next to the canvas JSON and the notebook, is enough. MkDocs publishes it with the rest of the documentation.

13. From pandas to PySpark

The Sprint 1 deliverable asks for the analysis in a Jupyter Notebook with Apache Spark. Pandas is convenient for the first exploration, because it is fast to write and the sample fits in memory, but Spark is the engine that the platform will use when the data grows. The procedure does not change between the two. Each check has a direct equivalent in the DataFrame API of PySpark, and the notebook of the deliverable can follow the same eight headings.

PySpark · inventory, grain, completeness, profile and orphans
from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.appName("eda").getOrCreate()
sales = spark.read.csv("data/sale_line.csv", header=True, inferSchema=True)
stock = spark.read.csv("data/stock_position.csv", header=True, inferSchema=True)
products = spark.read.csv("data/product.csv", header=True, inferSchema=True)

sales.count(); sales.printSchema()                                    # step 2
stock.groupBy("store_id", "product_id", "date").count().filter("count > 1").show()  # step 3
stock.select([F.avg(F.col(c).isNull().cast("int")).alias(c)
              for c in stock.columns]).show()                                 # step 4
sales.approxQuantile("quantity", [0.25, 0.75], 0.01)                     # step 5
sales.join(products, "product_id", "left_anti").count()                  # step 7

Two differences deserve attention. Spark computes quantiles approximately on large data, with a relative error that the analyst chooses, so the IQR fences may differ slightly from those of pandas. Spark also evaluates operations lazily, which means that nothing is computed until an action such as count or show is called, and an error in an early transformation may only appear at the action.

14. The Data Lake: zones, buckets and naming

A Data Lake stores data in its original or lightly processed form in an object store, which can be MinIO running in Docker during development or a bucket in a cloud provider. The value of the lake depends on its organisation. Without a convention, files accumulate under arbitrary names, and after a few weeks nobody can tell which extract is current, which system produced a file or whether two files contain the same data.

The initial structure of this lesson separates three zones. The landing zone receives files exactly as delivered, which preserves the evidence of what the partner sent. The raw zone holds the sample of each extract in Parquet, partitioned by ingestion date. The sandbox zone holds samples and intermediate files of the analysis, which may be deleted without loss. Lesson 3 reorganises these zones into the Bronze, Silver and Gold layers of the medallion architecture, and the form of the raw zone, whether an exact copy of the extract or a typed copy, is one of the decisions revisited there.

Convention · buckets and paths
<project>-landing/                         # files exactly as received
  pos/sale_line/2026-10-19/sale_line.csv

<project>-raw/                             # sample in Parquet
  <source>/<entity>/ingestion_date=YYYY-MM-DD/
  pos/sale_line/ingestion_date=2026-10-19/part-0.parquet
  erp/stock_position/ingestion_date=2026-10-19/part-0.parquet

<project>-sandbox/                         # samples and notebook outputs

Each part of the path carries information. The source names the system of origin, the entity names the information object of the canvas, and the ingestion date records when the data entered the platform. The form key=value is recognised as a partition by pandas, Spark and most query engines, which can then read only the dates that a query needs. The lineage of any file can therefore be read from its location, which anticipates the lineage field of the canvas.

15. Storing the sample in Parquet

Apache Parquet is a columnar file format. Instead of storing each row contiguously, as CSV does, it stores the values of each column together, along with the schema of the data and statistics for each block of values. Four consequences follow. A query that needs two columns of a wide table reads only those two columns. Dates and numbers keep their types, while in CSV every value is text that must be parsed again. Values of the same column, being similar, compress well. Finally, the statistics of each block allow readers to skip blocks that cannot satisfy a filter, which is called predicate pushdown.

pandas + pyarrow · write partitioned Parquet and read it back
sales["ingestion_date"] = "2026-10-19"

sales.to_parquet("lake/raw/pos/sale_line",   # local stand-in for the <project>-raw bucket
                 engine="pyarrow",
                 partition_cols=["ingestion_date"],
                 index=False,
                 existing_data_behavior="delete_matching",
                 basename_template="part-{i}.parquet")

back = pd.read_parquet("lake/raw/pos/sale_line")
display(back.dtypes)                     # compare with the inventory of step 2
len(back) == len(sales)                  # no rows lost

The two last arguments make the write idempotent. With existing_data_behavior="delete_matching", the partition of the day is replaced instead of receiving a new file, and basename_template gives the files a fixed name, so a notebook executed twice leaves the same rows in the lake instead of duplicating them and inflating every count read from it.

Reading the file back verifies the conversion. The types of the columns are compared with those recorded in the inventory of step 2, and the number of rows is compared with the original. A difference indicates a conversion problem, such as a date column stored as text, which is easier to correct now than after the Bronze layer depends on it. When the partition column is read back, pandas returns it as a categorical column, which is expected and does not indicate an error.

In Spark the same operation uses df.write.mode("overwrite").partitionBy("ingestion_date").parquet(path) with the setting spark.sql.sources.partitionOverwriteMode equal to dynamic, which replaces only the partitions present in the data and keeps the others. The resulting folder can be read by either library. This interoperability is one reason why Parquet is the common format of the module.

16. Conducting the procedure with an AI assistant

In this session the eight steps are conducted with the help of an AI assistant, which writes the code of each check and interprets its aggregated output. The procedure of the previous sections does not change, and the assistant changes only who writes the first version of each cell and of each sentence of the log.

The division of work between the group and the assistant follows from what each side can verify. The assistant writes pandas and PySpark code quickly and proposes hypotheses that a beginner would not consider, such as a grain finer than the declared one or a pattern of missing values tied to one store. It never sees the data, however, and it may therefore propose code that does not run on the real columns or causes that the output does not support, stated with the same confidence as the correct ones. For this reason the assistant proposes and the group decides. Every finding that enters the data quality log is reproduced by a cell of the notebook, and every number of the log is read from that cell and not from the reply of the assistant.

What may be sent to the assistant

The partner data is subject to the policies of block 8 of the canvas, starting with the LGPD, and a conversation with an external service takes the data outside the control of the group. The rule of the session is therefore that the assistant receives the description of the data and the results computed over it, and never the data itself. The rule also has a practical advantage, because a prompt with the schema and the aggregates is shorter and more precise than a prompt with thousands of rows.

May be sentIs never sent
Column names and types, as returned by df.dtypesRows of the partner data, including the output of head(), sample() or display(df)
Row counts, period covered and memory usedThe rows that a check found, such as the duplicated keys displayed side by side
Null rates, quantiles, counts of outliers and of invariant violationsFree-text fields, such as notes or descriptions written by operators
Frequencies of codes, such as store or product identifiersAny value of the personal or sensitive columns classified in block 8

Charts stay in the notebook. When a chart supports a finding, the group sends the aggregated series that produced it, such as the daily totals, or describes in one sentence what the chart shows.

The discovery loop

Each table is explored in a loop that alternates the group and the assistant, as in the diagram below. The group first sends the context of the table, which consists of the canvas assumptions, the schema and the inventory of Step 2, so that the assistant interprets every later output against the same assumptions. For each of Steps 3 to 7, the group then asks for the code of the check, reads it before running it, runs it in the notebook and returns only the aggregated output. The assistant interprets that output, lists the findings with their volume and marks what only the partner can decide, and the group checks each finding against the cell that produced it. Step 8 closes the loop by turning the verified findings into rows of the log and the rows into text for the canvas.

GroupContextCanvas assumptions, schema and inventory, once per table
AssistantAskCode of the check and the result expected if the canvas is right
GroupRun and returnThe cell runs in the notebook, and only aggregates go back
AssistantInterpretFindings, volume and probable causes supported by the output
GroupDecideEach finding is checked against its cell and recorded in the log

The four prompts

The context prompt is sent once, at the start of a new conversation for each table. It asks the assistant to wait for each step, which prevents it from writing the whole analysis at once, before the group has seen the output of the grain test that the later steps depend on.

Prompt 1 · Context, once per table
You are helping a data engineering team explore one table before its data
model is built. You will never receive rows of the data, only the canvas
assumptions, the schema and aggregated outputs that we compute ourselves.

Analytical question (canvas block 2): <question>
Table: <table>
Declared grain: one row per <entity, entity, period>
Key columns: <columns>
Invariants we expect: <list>
Related tables and join keys: <list>
Inventory from Step 2 (shape, dtypes, period covered):
<paste output>

Wait for each step before writing code.

The step prompt is repeated for Steps 3 to 7. It asks for code that prints only aggregates, which keeps the rule of this section in the code itself, and it asks the assistant to state in advance which result confirms the canvas, so that the group reads the output with an expectation and not after the fact.

Prompt 2 · One step, repeated for Steps 3 to 7
Step <n> · <name>. Question: <question of the step>.
Write pandas code for <table> that prints only aggregates (counts, rates,
quantiles, top-10 frequencies), never rows. Ask for: <what to compute>.
State the result that confirms the canvas and the result that would
contradict it.

The table below gives, for each step, the question and the computation that replace the placeholders of Prompt 2. The computations are those of sections 8 to 11, so the code returned by the assistant can be compared with the reference code of the material before it is run.

StepQuestion of the stepWhat to compute
3 · Structure and grainDoes the declared key identify each row?The number of repeated keys and, for the repeated keys, which columns differ between the copies
4 · CompletenessWhere are values missing, and following which pattern?The null rate of each column and, for the columns with nulls, the rate by store or another dimension and by week
5 · Univariate profileHow is each column distributed, and where are the outliers?Summary statistics of the measures, the cardinality of every column, the count of IQR outliers and the top-10 frequencies of the categorical columns
6 · RelationshipsHow do the variables move together and over time?Daily totals, the measure by category and the Spearman correlation between measures selected by name
7 · Consistency across tablesDo the joins and the invariants hold?The share of orphan rows of each join and the number of violations of each invariant

The interpretation prompt follows every run. It limits the causes to those that the output supports and asks the assistant to mark what the output cannot decide, which separates the findings that the group can record from the questions that go to the partner in block 6. It also forbids corrections, because the exploration measures and records, and the corrections belong to the Silver layer, as section 19 explains.

Prompt 3 · Interpretation, after each run
Output of Step <n>:
<paste aggregated output>

Compare it with the canvas assumptions. List each finding with its volume
and at most two probable causes that this output supports. Mark as
"ask the partner" what the output cannot decide, and do not propose
corrections to the data.

The last prompt corresponds to Step 8. It receives only the findings that the group confirmed in the notebook and asks for two products, the rows of the data quality log and a draft of the canvas blocks that the findings support. Requiring the finding ID behind each line keeps the correspondence between the canvas and the evidence, and allowing a block to stay empty prevents the assistant from filling the canvas with generic text that no finding supports.

Prompt 4 · Log and canvas, Step 8
Turn the verified findings below into rows of our data quality log, with the
columns ID | Table | Check | Finding and volume | Probable cause | Decision |
Canvas block. Use only blocks 4, 6, 14 and cube j as destinations.

Then draft the text of the cube blocks a (grain), d (facts), e (measures)
and f (dimensions), and of blocks 8 (policies) and m (classification),
citing the finding ID behind each line. Leave a block empty when no
finding supports it.

Findings confirmed in the notebook:
<paste list>

From the findings to the canvas

The draft returned by Prompt 4 is checked against the correspondence below, which extends that of section 3 to the blocks of the cube. A line of the draft whose block does not match the kind of finding, or whose finding ID does not exist in the log, is removed before the canvas is updated.

Kind of findingCanvas blockExample in the illustrative case
The declared key holds or repeatsCube a (grain) and 14One row per store, product and day, with 1.8% of keys repeated
Measures that the data supportsCube e (measures) and 4The share of stock-out days can be computed for every store
Dimensions with usable cardinalityCube f (dimensions)Store and product have stable codes, and the date covers the whole period
Questions that only the partner can answer6Whether sales above 200 units are orders from clinics
Checks that the pipeline must repeat14 and cube jThe grain test and the invariant on_hand >= 0
Personal or sensitive columns8 and cube mA customer identifier in the sale line, if the extract contains one
Keep the prompts with the evidence

Save the four prompts, filled in for each table, in /docs/data_model_canvas/prompts.md, next to the log and the notebook. The reviewer can then see what the assistant was asked and which of its suggestions the group kept.

17. The group practice of the session

The session reserves 45 minutes for each group to complete Steps 3 to 8 of the procedure with the AI assistant, following the loop and the prompts of section 16. The group first runs the cells on the synthetic data of the starter notebook, where the defects are known, and then applies the same cells to one table of the partner dataset that supports an analytical question of block 2 of the canvas. A table chosen without a question would turn the practice into the inventory that Lesson 1 warned against, and the synthetic run ensures that the code works before it meets the partner data. It also tests the assistant, because a finding that it proposes on the synthetic data can be compared with the defects that the notebook introduced on purpose.

The practice has three products. In the notebook, the group tests the grain, measures completeness, profiles the columns, examines the relationships and checks the consistency across tables, as in sections 8 to 11, keeping the cell that reproduces each finding proposed by the assistant. In the repository, the group records one row of the data quality log for each verified finding, with its volume, its probable cause, the decision taken and the canvas block it affects, using the template of section 12 and Prompt 4, and updates the canvas blocks that the log supports. In the Data Lake, the group writes the explored table as partitioned Parquet with the idempotent code of section 15 and reads it back to compare types and row counts.

The results of the practice are the material of the presentations that follow it, described in section 18. The steps that the group does not finish in class are completed before the Sprint Review on Friday, when the canvas and the analysis in Spark are delivered.

18. Presenting your results

The session closes with a presentation by each group of what it achieved on the partner data. The presentation is short, about four minutes per group followed by questions, and its purpose is to expose the findings to the class while they can still change the canvas, and before the Sprint Review on Friday. Presenting also forces the group to select, from everything the notebook computed, the findings that matter for the partner, which is the same selection that the data quality log requires.

Each presentation covers the same elements, so that the class can compare the groups. The group shows three findings with their volume, one invariant violation with its probable cause, the canvas block that each finding changes, the Parquet sample written to the raw zone with its path and row count, and the next step planned for the Friday deliverable. The figures are read from the notebook and the log, and not reconstructed from memory.

ElementWhat the group showsSource
Three findingsEach finding with its volume, such as the share of repeated keys or the null rate of one storeSteps 3 to 7 and the log
One invariant violationThe invariant, the number of violations and the probable causeStep 7 and the log
Canvas blocksThe block that each finding changes, such as 4, 6, 14 or j of the cubeLast column of the log
Parquet sampleThe path in the raw zone and the row count read backThe idempotent write
Next stepWhat the group will complete for the Friday deliverableThe plan of the group

After each presentation, the class asks one question to the group. A useful question asks for the evidence behind a finding, for the decision attached to it or for the reason why a defect was attributed to one cause and not another, including the causes suggested by the assistant that the notebook did not confirm. The professor uses the presentations to point out findings that recur across groups, which often indicate a property of the partner extract that should be confirmed with the partner.

19. Recurring mistakes

The most frequent mistake is to start the notebook with charts. Charts produced before the grain and the completeness are known may show duplicated data or gaps in the extract as if they were behaviour of the business, and the conclusions drawn from them must later be withdrawn. The order of the procedure exists to prevent this.

The second mistake is to correct the data during the exploration. Removing outliers, filling missing values or dropping orphan rows in the notebook hides the findings from the partner and introduces decisions that nobody recorded. The exploration measures and records, and the corrections are written later as rules of the Silver layer, where they can be reviewed and tested.

The third mistake is to keep the findings only in the notebook. A notebook is read from top to bottom and its outputs change at each execution, so it is a poor place for decisions. The data quality log, linked to the canvas, is where the findings become durable. The fourth mistake, finally, is to store the sample without a convention, under names such as final_v2.csv. The convention of section 14 costs a few minutes today and saves the reconstruction of lineage in later sprints.

Two mistakes are specific to the use of the AI assistant. The first is to paste the output of head() or the duplicated rows of Step 3 into the conversation, which sends partner data to an external service and breaks the rule of section 16. The second is to copy into the log a cause or a number that the assistant stated but that no cell of the notebook reproduces. The assistant writes plausible explanations with the same confidence whether or not the output supports them, so a finding enters the log only when the group can point to the cell that produced it.

20. Checklist

Use the list below before closing the exploration of each table. Click an item to mark it as done.

  • The project has a pyproject.toml with requires-python pinned to 3.12 and pandas<3, and a committed poetry.lock.
  • java -version reports Java 17 or later, and poetry run jupyter notebook opens on every machine.
  • Partner extracts are in a folder listed in .gitignore.
  • Before the session, the starter notebook ran up to Step 2 on the synthetic data.
  • The first cell states the analytical question, the declared grain and the invariants.
  • The inventory records rows, types, memory and the period covered.
  • The declared key was tested, and repeated rows were inspected.
  • Null rates were measured by column and broken down by store or period.
  • Each numeric column has a profile and an IQR outlier count.
  • Every chart kept in the notebook supports a sentence in the log.
  • Joins were tested for orphan rows, and invariants were counted.
  • Only the schema and aggregated outputs were sent to the AI assistant, never rows of the partner data.
  • Every finding proposed by the assistant is reproduced by a cell of the notebook.
  • Every finding has a row in the data quality log with a decision and a canvas block.
  • The canvas blocks drafted with Prompt 4 cite the finding ID behind each line, and the filled prompts are saved in prompts.md.
  • A sample was stored in the raw zone as Parquet, partitioned by ingestion date, with an idempotent write, and read back.
  • The presentation shows three findings with volume, one invariant violation, the canvas blocks, the Parquet path and row count, and the next step.

21. References