Instruction session · Monday, October 19, 2026
The exploratory analysis checks, in a notebook and with code, the information viewpoint that the group drafted in the Data Model Canvas. Steps 1 and 2 are run before class on synthetic data, and the session is spent on Steps 3 to 8 applied to the partner data, the data quality log, a first Parquet sample in the Data Lake and the presentation of what each group achieved.
Project ritual
Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.
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, record the findings in a data quality log, use the log to fill the Data Model Canvas, store a Parquet sample in the Data Lake and present the findings to the class.
The pre-class tasks were announced at the end of Lesson 1. They move the individual preparation out of the session, so that the time in class is spent on the partner data and on the discussion of its findings.
Python 3.12, Java 17 or later, Poetry and Jupyter in the group repository, following the checklist on the next slide.
Download lesson-2-starter.ipynb and open it with poetry run jupyter notebook. It generates the synthetic data itself.
Run the cell that generates the extract and the cells of Steps 1 and 2, and note what the inventory returns.
Sections 2 to 8 of the reading material, on the place of the analysis in the project and on Steps 1 to 4.
One member adopts the group repository with Poetry before the session, and the others run poetry install. The checklist is the first pre-class task, so that no time in class is spent installing software.
poetry init --no-interaction --python ">=3.12,<3.13" # pyproject.toml, under [tool.poetry]: 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
Without a pinned requires-python, Poetry resolves the dependencies for future Python versions and may refuse libraries that do not declare support for them.
PySpark 4 does not yet fully support pandas 3, and the Sprint 1 notebook runs both libraries in the same environment.
For a project that does not exist yet, poetry new <name> && cd <name> creates the standard layout.
Three questions about what the starter notebook returned, answered by show of hands and then explained by a volunteer. The answers indicate which steps the focused exposition needs to develop.
Step 2 displays the shape of stock_position. Does the number of rows equal stores times products times days, and what would a difference indicate?
Which type did the date column receive, and what would have happened to the period covered without parse_dates?
The declared grain is one row per product, store and day. What does a repeated key mean, and which two explanations must be told apart before deciding?
Reference for the focused exposition
Each step answers one question about the data and produces an entry in the data quality log. The order matters, because a later step depends on what the earlier ones established, such as the grain before the distributions.
stock_position, the declared grain is one row per store, product and day, so each combination of store_id, product_id and date should appear only once. Step 3 checks this by counting the rows that repeat the key.Done before class in the starter notebook.
Done before class in the starter notebook.
Does the declared key identify each row?
Where are values missing, and following which pattern?
How is each column distributed, and where are the outliers?
How do the variables move together and over time?
Do the joins and the invariants hold?
What enters the log, and which canvas block changes?
Reference for the focused exposition
The three panels show the same table, stock_position, in three situations, with its key columns highlighted.
stock_position| store_id | product_id | date | on_hand |
|---|---|---|---|
| 1 | 7 | 2026-08-01 | 12 |
| 1 | 7 | 2026-08-02 | 9 |
| 1 | 8 | 2026-08-01 | 15 |
| 2 | 7 | 2026-08-01 | 0 |
Every combination appears once, so counting rows counts store-product-days and summing on_hand gives the real stock.
stock_position| store_id | product_id | date | on_hand |
|---|---|---|---|
| 1 | 7 | 2026-08-01 | 12 |
| 1 | 7 | 2026-08-02 | 9 |
| 1 | 7 | 2026-08-02 | 9 |
| 1 | 8 | 2026-08-01 | 15 |
The same record was sent twice. The grain is correct, but the extract has a duplicate, and the stock of that day is counted as 18 instead of 9.
stock_position| store_id | product_id | date | on_hand |
|---|---|---|---|
| 1 | 7 | 2026-08-01 | 12 |
| 1 | 7 | 2026-08-02 | 9 |
| 1 | 7 | 2026-08-02 | 4 |
| 1 | 8 | 2026-08-01 | 15 |
The rows disagree, which points to a second count in the day or to a corrected resend. Only the partner can say which, and the answer may make the grain finer than declared.
The definition of the grain here is “one row of stock_position is the stock of one product, in one store, on one day”.
sale_line keeps one row per item of a receipt.
→
A daily summary keeps one row per store, product and day. A finer grain can always be aggregated into a coarser one, but never the reverse.
Reference for the focused exposition
The assistant writes the code of each check and interprets its aggregated output, while the group runs the code, reproduces every finding in the notebook and takes the decisions. The division follows from what each side can verify, since the assistant never sees the data and may propose causes that the output does not support.
Canvas assumptions, schema and the inventory of Step 2, sent once per table.
The assistant writes the check of the step and states the result that would confirm the canvas.
The group reads the code, runs it in the notebook and keeps the cell.
Only the aggregated output goes back: counts, rates, quantiles and frequencies.
The assistant lists findings and probable causes, and marks what only the partner can decide.
The group checks each finding against the cell that produced it and writes the log row.
Column names and types, row counts, null rates, quantiles, counts of invariant violations and frequencies of codes such as store or product identifiers.
Rows of the partner data, including the output of head() or sample(), free-text fields and any value of the personal or sensitive columns classified in block 8 under the LGPD.
Reference for the focused exposition
The context prompt is sent once per table. The step prompt is repeated for Steps 3 to 7 with the question of each step from slide 7, and the interpretation prompt follows every run, with the aggregated output in place of the placeholder.
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): <paste output> Wait for each step before writing code.
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. State the result that confirms the canvas and the result that would contradict it.
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.
Reference for the focused exposition
Step 8 turns the verified findings into rows of the log and the rows into text for the canvas. The assistant drafts both, and the group keeps a line only when it can point to the notebook cell that supports it.
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>
| Finding | Canvas block |
|---|---|
| Declared key holds or repeats | Cube a · 14 |
| Measures the data supports | Cube e · 4 |
| Dimensions with usable cardinality | Cube f |
| Questions only the partner answers | 6 |
| Checks the pipeline must repeat | 14 · cube j |
| Personal or sensitive columns | 8 · cube m |
Reference for the focused exposition
The grain is tested before the distributions, because duplicated rows inflate every count that follows. Missing values are then measured column by column and broken down by the dimension that may explain them.
If the declared key repeats, either the grain is different from what the group assumed or the extract contains duplicates. The repeated rows are inspected side by side before deciding which case applies.
key = ["store_id", "product_id", "date"]
stock.duplicated(subset=key).sum()
(stock[stock.duplicated(subset=key, keep=False)]
.sort_values(key).head(20))A null rate concentrated in one store or one period points to a failure of the process that produced the data, which is reported to the partner and not imputed silently.
stock.isna().mean().sort_values(ascending=False)
(stock.groupby("store_id")["on_hand"]
.apply(lambda s: s.isna().mean())
.sort_values(ascending=False))Reference for the focused exposition
The univariate profile describes each column on its own. Numeric columns receive summary statistics and an outlier rule, and categorical columns receive their cardinality and most frequent values.
display(sales["quantity"].describe()) display(sales.nunique().sort_values()) 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)
The interquartile rule marks values beyond 1.5 times the IQR. A sale of 400 units may be a typing error or a wholesale order, and only the partner can say which.
A column with one value carries no information, and a code column with as many values as rows is an identifier, which changes how it is modelled.
Reference for the focused exposition
Relationships are examined in three forms: over time, between categories and between numeric measures. Each form answers a different part of the analytical question, and each chart is kept only if it supports a sentence in the log.
Daily totals reveal seasonality, gaps in the extract and changes of level that a single average hides.
daily = (sales .groupby(sales.sold_at.dt.date) ["quantity"].sum()) daily.plot()
The share of stock-out days in each store is a first draft of the KPI. The full KPI of Lesson 1 also keeps only continuous-use products and groups by week and product.
key = ["store_id", "product_id",
"date"]
obs = (stock
.dropna(subset=["on_hand"])
.drop_duplicates(key,
keep="last"))
(obs["on_hand"].le(0)
.groupby(obs["store_id"])
.mean())Spearman correlation tolerates skew and outliers. The measures are selected by name, so identifiers stay out of the matrix.
daily_sp = (sales
.assign(date=sales.sold_at
.dt.normalize())
.groupby(key, as_index=False)
["quantity"].sum()
.merge(obs, on=key))
(daily_sp[["quantity", "on_hand"]]
.corr(method="spearman"))Reference for the focused exposition
The relationships declared in the information viewpoint are tested with joins, and the invariants are tested with filters. A join that loses rows changes every indicator built on it, so its volume is measured before the join is used.
The indicator argument marks rows that found no match. Their share decides whether the join can be used as it is or needs a treatment in the Silver layer.
m = sales.merge(products, on="product_id",
how="left", indicator=True)
display((m["_merge"] == "left_only").mean())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.
display((stock["on_hand"] < 0).sum()) display((sales["quantity"] <= 0).sum()) display((sales["sold_at"] > pd.Timestamp.now()).sum())
Reference for the focused exposition
Every finding of the previous steps becomes one row of the log, with its volume, its probable cause and the decision taken. The last column links the finding to the canvas block it changes.
| ID | Table | Check | Finding and volume | Probable cause | Decision | Canvas block |
|---|---|---|---|---|---|---|
| DQ-01 | stock_position | Grain | 1.8% of keys repeat | Store count sent twice | Record the volume; the treatment in Silver is decided in Lesson 3 | 14 · cube j |
| DQ-02 | stock_position | Completeness | On-hand missing in 2 stores | Stores without daily count | Ask the partner | 6 |
| DQ-03 | sale_line | Orphans | 0.4% of lines without product | Product table extracted earlier | Quarantine | 14 |
| DQ-04 | sale_line | Outliers | 31 lines above 200 units | Possible wholesale orders | Validate with the partner | 4 · 6 |
Reference for the focused exposition
Spark splits the table into partitions and processes them on several executors at the same time. The animation follows the grain check of Step 3 on the rows of slide 8, from the plan built in the driver to the single row that returns to it.
(stock
.groupBy(key)
.count()
.filter("count > 1")
.show())
Reference for the focused exposition
The Sprint 1 deliverable asks for the analysis in a Jupyter Notebook with Apache Spark. Each check of the procedure has a direct equivalent in the DataFrame API, so the pandas exploration of today becomes the Spark notebook of the deliverable.
| Step | pandas | PySpark |
|---|---|---|
| 2 · Inventory | df.shape, df.dtypes | df.count(), df.printSchema() |
| 3 · Grain | df.duplicated(subset=key).sum() | df.groupBy(key).count().filter("count > 1") |
| 4 · Completeness | df.isna().mean() | df.select([F.avg(F.col(c).isNull().cast("int")).alias(c) for c in df.columns]) |
| 5 · Profile | df["q"].quantile([.25, .75]) | df.approxQuantile("q", [0.25, 0.75], 0.01) |
| 6 · Relationships | df.groupby(...).sum() | df.groupBy(...).agg(F.sum("q")) |
| 7 · Orphans | merge(..., indicator=True) | sales.join(products, "product_id", "left_anti").count() |
Reference for the focused exposition
The partner data fits on a single laptop, so a real cluster would add cost without adding learning. Each tool below runs locally and makes one concept of the architecture visible. The Sprint 1 deliverable still requires the notebook in Apache Spark.
Starts a scheduler and several workers on the cores of the machine. The dashboard shows each task on a timeline, the memory of each worker and the data moved between them while the computation runs.
from dask.distributed \
import Client
c = Client(n_workers=4)
c.dashboard_linkDistributes Python functions as remote tasks and keeps state inside actors, which are objects that live on a worker and answer calls asynchronously. It is a common base for training and serving AI models.
ray.init()
@ray.remote
class Counter:
def add(self, n): ...One master container and two worker containers on the same machine reproduce the roles of a Spark cluster, with the Spark UI on port 8080, at no cloud cost. The notebook of the deliverable connects to the master.
SparkSession.builder \ .master( "spark://localhost:7077")\ .getOrCreate()
Reads the Parquet folders of the raw zone, written as ingestion_date=YYYY-MM-DD/, and skips the folders the filter excludes. The same pruning is how Spark avoids reading a whole bucket in S3.
FROM read_parquet( 'sale_line/*/*.parquet', hive_partitioning=true) WHERE ingestion_date = '2026-10-19'
Each group completes the empty cells of the starter notebook on the synthetic data, where the defects are known, and then applies the same cells to one partner table that supports a question in block 2 of the canvas. The practice lasts 45 minutes.
Steps 3 to 7 on the chosen partner table with Prompts 1 to 3, keeping in the notebook the cell that reproduces each finding. The last cell writes the table as Parquet and reads it back.
Step 8 with Prompt 4: one row of the data quality log for each verified finding, and the canvas text that the log supports. The template is in section 12 of the material.
The five elements of the presentation that closes the session: three findings, one invariant violation, the canvas blocks, the Parquet sample and the next step.
.gitignore, and only aggregated outputs are pasted into the assistant. The notebook, the lock file, the log and the prompts used are committed.Reference for the group practice
The Data Lake stores the partner data in an object store, such as MinIO running in Docker or a cloud bucket. A naming convention decided now keeps every later layer findable. Lesson 3 organises these zones into the Bronze, Silver and Gold layers and revisits whether the raw zone keeps an exact or a typed copy.
<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/ notebooks and samples
The path names the system of origin and the information object, so the lineage of a file can be read from its location.
The key=value form is understood as a partition by pandas, Spark and query engines, which read only the dates a query needs.
Reference for the group practice
Parquet is a columnar format that stores the schema with the data. The write replaces the partition of the day, so a rerun does not duplicate rows. Reading the file back and comparing its types with the inventory of step 2 verifies the conversion.
sales["ingestion_date"] = "2026-10-19"
# local stand-in for the <project>-raw bucket
sales.to_parquet("lake/raw/pos/sale_line",
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 step 2
len(back) == len(sales)A query that needs two columns reads two columns, which reduces input and output on wide tables.
Dates and numbers keep their types, unlike CSV, where every value is text.
Values of the same column compress well together, which reduces storage cost.
Column statistics let readers skip blocks that cannot match a filter.
About four minutes per group, followed by questions. Each group presents the same elements, read from its notebook and its data quality log, so that the class can compare the findings across groups.
Each one with its volume, such as the share of repeated keys or the null rate of one store.
The invariant, the number of violations and the probable cause.
The block that each finding changes: 4, 6, 14 or j of the cube.
The path in the raw zone and the row count read back.
What the group will complete for the deliverable on Friday.
The exploratory notebook of today is the evidence that supports the canvas. Both graded deliverables of Sprint 1 are presented on Friday, October 23, at the Sprint Review and Retrospective.
The complete canvas and the analysis in a Jupyter Notebook with Apache Spark, stored under /docs/data_model_canvas/. The data quality log feeds blocks 4, 6 and 14.
Market sizing and risk management, starting with the Value Proposition Canvas, in /docs/Market-and-Risk-Analysis-Workbook.md.
The Bronze, Silver and Gold layers, followed by one hour of the graded Architecture Activity in class. The zones designed today are its starting point.
Three readings assigned on Adalove for this session, about 120 minutes in total, with no grade weight.
A GitHub repository with a step-by-step guide to exploratory analysis organised in reusable functions, for finding patterns and relationships and preparing a dataset for further analysis.
The management of data from creation and collection to storage, transformation, consumption and deletion or archival.
The phases of the analytics lifecycle and how each one builds on the previous to turn raw information into decisions.
Advanced Exploratory Data Analysis · 19/10/2026 · Prof. Afonso
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.
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.