For three modules you have worked as Laura, the data engineer, would: storing, cleaning, transforming and automating. NovaMarket's lake has a reliable silver zone and a gold zone with a star schema and a daily funnel. Now the main character changes. Marc, the analyst, has no wish to maintain pipelines: he wants answers. Which category is driving sales? Which customers are about to stop buying? Did the May campaign work?
To answer, he has a range of tools that, seen from the outside, appear to compete with one another: SQL engines, pandas, notebooks, machine learning libraries, BI tools. In reality they share out the work. This lesson draws the map, explains what each family solves and gives you a criterion for choosing. And you will check it in practice: you will answer the same business question with three different tools and compare the result, the time taken and the convenience.
From the lake to the answer: what an analyst needs
An analyst's work is not a straight line but a cycle: you pose a question, query the data, look at the result, and that result suggests the next question. What analysts value most is for that cycle to be short. If each query takes ten minutes, they will ask six questions in an hour; if it takes two seconds, they will ask hundreds, and the quality of the analysis changes completely.
From this come the three variables that set analysis tools apart:
- The volume they handle. Some work with whatever fits in a laptop's memory; others spread the work across hundreds of machines.
- Response latency. Here "latency" is not the latency of the data (lesson 03-05), but how long the tool takes to answer: milliseconds, seconds or minutes.
- The profile of the user. A director looking at a dashboard is not the same as a data scientist programming a model.
The full journey, from the lake to whoever makes the decision, breaks down like this:
flowchart LR
L[("Lake / lakehouse<br>silver and gold")] --> M["SQL engines<br>Trino, Spark SQL,<br>cloud DW, DuckDB"]
M --> A["Analysis languages<br>Python (pandas, Polars), R"]
M --> B["BI tools<br>Tableau, Power BI, Superset"]
A --> ML["ML libraries<br>scikit-learn, MLlib"]
C["Notebooks<br>Jupyter and managed"] -.working environment.-> M
C -.-> A
C -.-> ML
B --> D(["Decision"])
A --> D
ML --> D
SQL engines are the gateway to big data: they reduce millions of rows to a manageable result. The analysis languages, the ML libraries and the BI tools work on that result. Notebooks are not one more link in the chain, but the desk where all the others are combined.
Interactive SQL engines
Half a century after its invention, SQL is still the common language of data analysis. Analysts, engineers and almost every tool understand it. An interactive SQL engine is a system capable of running SQL queries directly on the lake's files (Parquet, Delta or Iceberg tables) and returning the answer quickly enough to keep the question cycle going.
Distributed engines on the lake
- Trino (and Presto, the project it comes from). A distributed SQL engine with an MPP architecture (lesson 02-05), built for interactive queries. It does not store data: it connects to it through connectors (a lake in object storage, a relational database, Kafka, MongoDB...). Its distinctive feature is the federated query: a single
SELECTcan join a table in the lake with another that lives in the shop's database. It works mainly in memory and is designed for queries lasting seconds or a few minutes, not for transformations lasting hours. - Spark SQL. You have known it since lesson 03-02. It is the same engine you use with DataFrames, with a different syntax. It copes well with huge, long-running queries, because it tolerates failures midway through execution, but starting a session takes several seconds and its minimum latency is higher. It is the natural choice when the query is part of a pipeline or when you are already working on a Spark-based platform.
- Cloud data warehouse and lakehouse engines. The services you placed on the map in lesson 02-05 (BigQuery, Snowflake, Redshift, the Databricks SQL engine, Athena, which is Trino offered as a service) are, from the analyst's point of view, managed SQL engines: you write the query and the provider supplies the machines. They are covered in lesson 06-04.
DuckDB: analysis on a single machine
DuckDB represents the opposite idea: no cluster at all. It is an embedded analytical database: there is no server to install or start; it is a library that runs inside your own Python program (just like SQLite, but designed for analysis rather than transactions). Internally it is columnar and makes use of all the machine's cores. Three properties have made it very popular among analysts:
- It reads Parquet directly, without loading anything first:
SELECT ... FROM 'path/*.parquet'. It takes advantage of the column pruning and predicate pushdown you saw in lesson 02-02. - It does not need the data to fit in memory: it processes in blocks and can use the disk, so on a laptop it comfortably handles tens of gigabytes.
- It gets on well with pandas: it can query a pandas DataFrame with SQL and return the result as another DataFrame.
DuckDB has made an awkward but healthy question fashionable: do you really need a cluster? Many datasets that required Hadoop ten years ago fit on a single modern machine today. For NovaMarket's gold tables, which are small by design, DuckDB is an excellent tool. For the 2.79 TB of raw events a year, it is not: a distributed engine is still needed there.
| Engine | Where it runs | Strength | Limitation |
|---|---|---|---|
| Trino / Presto | Your own cluster or a managed service | Interactive, federated queries over many sources | Not well suited to very long processes |
| Spark SQL | Spark cluster (or local mode) | Massive queries and transformations; same engine as the pipelines | Slow start-up; minimum latency of seconds |
| Cloud DW/lakehouse engines | The provider's service | No administration; elastic scaling | Pay-per-use cost that needs watching; vendor lock-in |
| DuckDB | Your own process, one machine | Immediate, no infrastructure; reads Parquet directly | A single machine: it does not scale horizontally |
Analysis languages and libraries
SQL is very good at answering "how much" and "how many", but it falls short for statistics, models or free-form data manipulation. That is where analysis languages come in.
- Python is the dominant language today. Its core library is pandas, which you have known since lesson 01-02: it offers the in-memory DataFrame, convenient and with a vast ecosystem around it (charts, statistics, ML). Its limit is well known: it works on a single machine, almost always with a single core, and it needs the data and several intermediate copies to be held in memory. The usual rule is to have several times the size of the data in RAM.
- Polars is a more recent DataFrame library, written in Rust. It uses all the cores, has a lazy evaluation mode with an optimiser (the same idea you saw in Spark) and can process files larger than memory. Its syntax differs from that of pandas. It is a good option when pandas becomes slow but a cluster would be overkill.
- R is a language born for statistics. It remains very strong in academia, biostatistics and research, with excellent libraries for statistical models and charts. Like pandas, it works in memory; for big data it connects to Spark or to a SQL engine.
- SAS is the historic commercial tool for statistical analysis. For decades it was the standard in banking, insurance and pharmaceuticals, and it is still present in those sectors because of the number of validated processes that depend on it. New projects tend to opt for Python or R, which are free; but you are likely to come across SAS if you work at a large financial institution.
As a bridge between the two worlds, Spark offers the pandas API on Spark (pyspark.pandas), which lets you write code with pandas syntax and run it in a distributed way. It is useful for migrating existing code, although not every operation has an efficient equivalent.
Notebooks
A notebook is an interactive document made up of cells. Some contain code, which runs cell by cell and shows the result just below it (a table, a chart); others contain explanatory text. The result combines reasoning, code and evidence in a single document.
- Jupyter is the open-source standard. If you installed it in lesson 01-05, you can open it with
jupyter labfrom~/novamarketand use all the course code in it: one cell creates theSparkSession, and the following ones run queries on it without starting it again. - Notebooks on managed platforms. Databricks, the cloud providers' data science services (lesson 06-04) and Google Colab offer notebooks already connected to a cluster and to the data catalogue, with collaborative editing, and they usually let you mix SQL and Python cells.
Notebooks fit the analyst's cycle perfectly, which is why they are the preferred environment for exploring. They also have drawbacks that are worth knowing from the outset:
| Advantage | Drawback |
|---|---|
| Immediate result under each cell | Cells can be run in any order: the notebook may show results that can no longer be reproduced when it is run from top to bottom |
| Code, text and charts together: the analysis explains itself | Hard to review and version with git (the file mixes code and results) |
| The session stays alive: nothing is reloaded for each test | They tend to grow without structure or tests |
| Easy to share as a report | A poor basis for production processes |
The sensible practice: explore in notebooks and move whatever must run periodically into scripts. That is why daily_load.py is a script, and why the course exercises are written as scripts, which work the same whether or not you have Jupyter; if you prefer, you can paste each snippet into a cell.
Machine learning libraries and BI tools
Two families remain that this lesson only places on the map, because each has its own lesson.
Machine learning libraries and platforms. They are used to train models that predict, classify or group. They are covered in lesson 04-03.
- scikit-learn: the reference library for classical ML in Python. It works in memory, on one machine.
- Spark MLlib: Spark's ML library. It trains in a distributed way on data that does not fit on one machine.
- TensorFlow and PyTorch: deep learning (neural network) libraries, designed for training on GPUs.
BI and visualisation tools. They turn data into interactive charts and dashboards, with no programming, for decision-makers. Internally they generate SQL and send it to an engine. They are dealt with in lessons 04-04 and 04-05.
- Tableau and Power BI: the two most widespread commercial tools.
- Apache Superset: the open-source alternative.
- Looker: Google Cloud's BI platform, centred on defining metrics only once.
Comparison: which tool for which situation
| Tool | Comfortable data volume | User profile | Response latency | Use it when... |
|---|---|---|---|---|
| pandas / R | Whatever fits in memory (up to a few GB) | Analyst, data scientist | Milliseconds to seconds | The data is already small or aggregated |
| Polars | Up to tens of GB on one machine | Analyst, data scientist | Milliseconds to seconds | pandas becomes slow or runs out of memory |
| DuckDB | Up to tens or hundreds of GB on one machine | Analyst who knows SQL | Milliseconds to seconds | You want SQL on Parquet without infrastructure |
| Trino / Presto | Terabytes to petabytes | Analyst who knows SQL; BI tools | Seconds to minutes | Interactive or federated queries on the lake |
| Cloud DW/lakehouse engines | Terabytes to petabytes | Analyst who knows SQL; BI tools | Seconds to minutes | Your platform is already in that cloud |
| Spark (SQL and DataFrames) | Terabytes to petabytes | Data engineer, data scientist | Seconds to hours | Heavy transformations, pipelines, distributed ML |
| Spark MLlib | Terabytes | Data scientist, ML engineer | Minutes to hours | Training does not fit on one machine |
| scikit-learn | Whatever fits in memory | Data scientist | Seconds to minutes | The training set fits in memory |
| BI tools | That of the engine they connect to | Business user, analyst | Seconds | Recurring consumption: dashboards and reports |
The volume figures are a rough guide: they depend on the machine and the type of query. The underlying criterion comes down to three questions, in this order:
- Where is the data and how large is it? If it does not fit on one machine, the first tool has to be distributed.
- Who is going to use the result? A dashboard for Irene calls for a BI tool; an exploration by Marc, a notebook with SQL and pandas.
- How often is it repeated? Something run once can live in a notebook; anything recurring belongs in an orchestrated pipeline (lesson 03-06).
And one observation that saves a lot of arguments: tools are combined. Marc's normal day starts with a SQL query on the lakehouse, continues in pandas inside a notebook and ends in a BI dashboard.
Hands-on: one question, three tools
Irene asks Marc for a table for the committee: sales by category and month, excluding returns. The data is in the gold zone: fact_sales (one row per order line, 50,107 rows), dim_product and dim_date. In lesson 02-05 you ran a similar query with Spark; now you will answer it in three ways.
First, install what is missing in the virtual environment:
duckdb is the engine; pyarrow is the library pandas needs to read Parquet.
With Spark SQL
Create ~/novamarket/query_spark.py:
import time
from pathlib import Path
from pyspark.sql import SparkSession
GOLD = Path.home() / "novamarket" / "lake" / "gold"
start = time.perf_counter()
spark = SparkSession.builder.master("local[*]").appName("query_spark").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
for table in ("fact_sales", "dim_product", "dim_date"):
spark.read.parquet(str(GOLD / table)).createOrReplaceTempView(table)
result = spark.sql("""
SELECT p.category,
d.month,
ROUND(SUM(f.line_amount), 2) AS sales
FROM fact_sales f
JOIN dim_product p ON f.product_id = p.product_id
JOIN dim_date d ON f.date_id = d.date_id
WHERE f.status <> 'returned'
GROUP BY p.category, d.month
ORDER BY p.category, d.month
""")
result.show(8)
print(f"Total time: {time.perf_counter() - start:.1f} s")
spark.stop()There is nothing new here: each table is registered as a temporary view and the query joins the facts with two dimensions. time.perf_counter() is a Python stopwatch; timing starts before the session is created so as to include the start-up.
+----------+-----+---------+ | category|month| sales| +----------+-----+---------+ |appliances| 1|769906.47| |appliances| 2|625808.56| |appliances| 3|717000.04| |appliances| 4| 684169.9| |appliances| 5|694492.56| |appliances| 6|680554.23| | audio| 1|764935.12| | audio| 2|663824.89| +----------+-----+---------+ only showing top 8 rows Total time: 6.5 s
The full result has 36 rows: 6 categories by 6 months. The time will vary on your machine, but note the order of magnitude: several seconds, almost all of them spent starting the Java virtual machine and the session.
With DuckDB
Create ~/novamarket/query_duckdb.py:
import time
from pathlib import Path
import duckdb
GOLD = Path.home() / "novamarket" / "lake" / "gold"
start = time.perf_counter()
result = duckdb.sql(f"""
SELECT p.category,
d.month,
ROUND(SUM(f.line_amount), 2) AS sales
FROM read_parquet('{GOLD}/fact_sales/*.parquet') f
JOIN read_parquet('{GOLD}/dim_product/*.parquet') p ON f.product_id = p.product_id
JOIN read_parquet('{GOLD}/dim_date/*.parquet') d ON f.date_id = d.date_id
WHERE f.status <> 'returned'
GROUP BY p.category, d.month
ORDER BY p.category, d.month
""")
result.show(max_rows=8)
print(f"Total time: {time.perf_counter() - start:.2f} s")- There is no session, no server and no views to register.
duckdb.sql(...)runs the query in a temporary in-memory database. read_parquet('.../*.parquet')reads the Parquet files in the folder. The*.parquetwildcard avoids the auxiliary files Spark leaves behind (_SUCCESSand the.crcfiles).- The SQL is the same. Only where the tables come from changes. That portability is one of SQL's great strengths.
.show()prints the result;result.df()would return it as a pandas DataFrame.
┌────────────┬───────┬────────────┐ │ category │ month │ sales │ │ varchar │ int32 │ double │ ├────────────┼───────┼────────────┤ │ appliances │ 1 │ 769906.47 │ │ appliances │ 2 │ 625808.56 │ │ appliances │ 3 │ 717000.04 │ │ appliances │ 4 │ 684169.9 │ │ · │ · │ · │ │ · │ · │ · │ │ · │ · │ · │ │ television │ 3 │ 1687971.87 │ │ television │ 4 │ 1600170.22 │ │ television │ 5 │ 1785911.07 │ │ television │ 6 │ 1600253.92 │ └────────────┴───────┴────────────┘ 36 rows (8 shown) 3 columns Total time: 0.03 s
The same figures, in hundredths of a second. To read a partitioned table, such as silver/web_events, you add a level to the wildcard and ask it to interpret the date=... folders as a column: read_parquet('.../silver/web_events/*/*.parquet', hive_partitioning=true).
With pandas
Create ~/novamarket/query_pandas.py:
import time
from pathlib import Path
import pandas as pd
GOLD = Path.home() / "novamarket" / "lake" / "gold"
start = time.perf_counter()
facts = pd.read_parquet(GOLD / "fact_sales",
columns=["date_id", "product_id", "status", "line_amount"])
products = pd.read_parquet(GOLD / "dim_product", columns=["product_id", "category"])
dates = pd.read_parquet(GOLD / "dim_date", columns=["date_id", "month"])
result = (
facts[facts["status"] != "returned"]
.merge(products, on="product_id")
.merge(dates, on="date_id")
.groupby(["category", "month"], as_index=False)["line_amount"].sum()
.rename(columns={"line_amount": "sales"})
.round({"sales": 2})
)
print(result.head(8))
print(f"Memory used by facts: {facts.memory_usage(deep=True).sum() / 1e6:.1f} MB")
print(f"Total time: {time.perf_counter() - start:.2f} s")pd.read_parquet(..., columns=[...])loads only the specified columns into memory: column pruning, requested by hand.facts[facts["status"] != "returned"]is theWHERE;.merge(...), theJOIN;.groupby(...).sum(), theGROUP BYwith itsSUM.memory_usage(deep=True)tells you how much memory the DataFrame takes up.
category month sales 0 appliances 1 769906.47 1 appliances 2 625808.56 2 appliances 3 717000.04 3 appliances 4 684169.90 4 appliances 5 694492.56 5 appliances 6 680554.23 6 audio 1 764935.12 7 audio 2 663824.89 Memory used by facts: 1.6 MB Total time: 0.04 s
What the comparison teaches
| Spark SQL | DuckDB | pandas | |
|---|---|---|---|
| Result | Identical | Identical | Identical |
| Time (approximate) | ~6 s | ~0.03 s | ~0.04 s |
| Preparation | Session and temporary views | None | Loading the tables into memory |
| How it is expressed | SQL (or DataFrames) | SQL | Chained methods |
| Where the data is during the calculation | Spread across executors | On disk, read in blocks | All in memory |
If fact_sales had 50 billion rows |
It would work, with a suitable cluster | Not on one machine | Out-of-memory error |
With 50,107 rows, Spark is by far the slowest, and that is not a defect: it is paying the fixed cost of machinery designed to share work out across hundreds of machines. It is the same lesson you learnt with MapReduce in 03-01: the overhead of a distributed system only pays off when the volume demands it. The last row of the table is the other side of the coin: as the data grows, pandas is the first to fall, DuckDB holds out much longer and only Spark (or an equivalent distributed engine) makes it to the end.
At NovaMarket, the real division of labour would be this: the 40 million daily events are processed with Spark; the gold tables, already aggregated, are queried with the lakehouse's SQL engine or, on Marc's laptop, with DuckDB; and the fine-grained analysis is finished in pandas.
The golden rule: aggregate big, analyse small
Almost no analysis needs to see every row. What it needs is the result of summarising them: 36 sales figures, 31 days of funnel, a sample of 10,000 sessions. From this comes the most useful working rule in the module:
Aggregate big, analyse small. Reduce the data with the distributed engine (filter, join, aggregate or sample) until the result is small, and only then bring it down to a single-machine tool for fine-grained analysis, statistics and charts.
flowchart LR
A["Massive data<br>millions of rows<br>(lake)"] -->|"filter, join, aggregate<br>Spark / SQL engine"| B["Small result<br>tens or thousands of rows"]
B -->|"toPandas()"| C["pandas on the driver<br>statistics, charts, report"]
In Spark, the bridge is the toPandas() method, which converts a Spark DataFrame into a pandas one. Add these lines to query_spark.py, before spark.stop():
# Only the 36 rows of the result travel to the driver
report = result.toPandas()
pivot = report.pivot(index="category", columns="month", values="sales")
pivot["total"] = pivot.sum(axis=1)
print((pivot / 1000).round(0).astype(int)) # in thousands of eurostoPandas() is an action: it runs the query and brings all the rows of the result into the driver's memory. From then on, report is an ordinary pandas DataFrame, and pivot rotates it so that each month becomes a column:
month 1 2 3 4 5 6 total category appliances 770 626 717 684 694 681 4172 audio 765 664 738 714 755 721 4356 computing 1035 836 931 945 1004 901 5652 home 453 385 476 426 453 406 2598 phones 904 843 912 846 898 813 5216 television 1727 1502 1688 1600 1786 1600 9904
This is the table Marc sends to Irene: television is the top category, with €9.9 million in the half-year, almost four times what home sells. The sum of the total column, €31.9 million, matches the sales excluding returns that you calculated in lesson 03-03 (€31,898,257.53). Checking that a new figure tallies with one you already know is a habit that saves a lot of grief.
Depending on the version of pandas installed, toPandas() may display a warning (FutureWarning) about compatibility between PySpark and pandas versions. It does not affect these examples.
The rule has a downside you must not forget: toPandas() on a large DataFrame tries to fit everything into the driver's memory and brings it down, exactly like collect() (lesson 03-02). Before calling it, ask yourself how many rows the result has; if you do not know, count them or limit them:
print(result.count()) # how many rows am I going to bring back?
sample = events.limit(10_000).toPandas() # if it is large, cap it firstCommon Mistakes and Tips
- Using Spark for everything. Spinning up a cluster to query a 36-row table is slow and expensive. If the data is already small, use a small tool.
- Using pandas for everything. The mirror-image mistake: loading the whole file "because the sample fits on my laptop". In production the data is a thousand times larger.
- Calling
toPandas()without knowing the size. This is the most common way to exhaust the driver's memory. Aggregate, filter or limit first. - Bringing the data back in order to filter it afterwards.
df.toPandas()followed by a filter in pandas does the work back to front. The filter goes first, in the engine. - Forgetting the wildcard in DuckDB.
read_parquet('folder')does not read a folder; you need to specifyfolder/*.parquet. - Comparing times without context. DuckDB winning with 50,000 rows does not mean it wins with 50 billion. Benchmarks are only valid for the volume they were run with.
- Choosing the tool because it is fashionable. The criterion is volume, user and frequency, not whatever is in vogue this year.
- Leaving a recurring analysis in a notebook. If someone runs it by hand every Monday, it should be an orchestrated script.
- Tip: when two tools give different figures for the same question, do not pick the one you like best: find out why. It is almost always a different filter (here, returns) or a different treatment of nulls.
Exercises
Exercise 1: choosing the tool
State which tool (or combination) you would use in each NovaMarket situation and why:
- Irene wants to see the previous day's sales by category every morning, without writing any code.
- Marc wants to count how many events of each type there were over the whole of last year (some 14.6 billion events, 2.79 TB).
- Marc has an 8 GB Parquet export on his laptop with three years of order lines and wants to calculate the average order value by province.
- A data scientist wants to study the relationship between price and units sold for the 200 products.
- Laura needs to join, in a single query, a table in the lake with the stock table that lives in the warehouse's database.
Exercise 2: the funnel with DuckDB
Without using Spark, query the gold/daily_funnel table (partitioned by date) with DuckDB and obtain June's total sessions and sessions with a purchase, and the conversion rate as a percentage. Compare the result with what you know from lesson 03-06.
Exercise 3: aggregate big, analyse small
With Spark, calculate from silver/orders_complete the number of orders and the average amount by channel and status. Move the result to pandas with toPandas() and, once in pandas, build a table with the statuses in the rows, the channels in the columns and the number of orders in the cells. How many rows travel to the driver?
Solutions
Exercise 1
- A BI tool connected to the lakehouse's SQL engine, on top of a gold table. This is recurring consumption by a business user.
- A distributed engine: Spark SQL or the lakehouse's SQL engine (or Trino). With 2.79 TB there is no single-machine alternative; the result, four rows, can be viewed anywhere.
- DuckDB (or Polars). 8 GB of Parquet does not fit comfortably into a laptop's memory for pandas, but DuckDB processes it in blocks without any trouble, and there is nothing to set up.
- pandas (or R), in a notebook. It is 200 rows: what matters here is statistical and charting convenience, not scale. The sales data by product is aggregated beforehand with SQL.
- Trino, because of its ability to run federated queries across the lake and a relational database.
Exercise 2
from pathlib import Path
import duckdb
GOLD = Path.home() / "novamarket" / "lake" / "gold"
duckdb.sql(f"""
SELECT SUM(sessions) AS sessions,
SUM(with_purchase) AS with_purchase,
ROUND(100.0 * SUM(with_purchase) / SUM(sessions), 2) AS conversion_pct
FROM read_parquet('{GOLD}/daily_funnel/*/*.parquet', hive_partitioning=true)
""").show()┌──────────┬───────────────┬────────────────┐ │ sessions │ with_purchase │ conversion_pct │ │ int128 │ int128 │ double │ ├──────────┼───────────────┼────────────────┤ │ 30952 │ 3736 │ 12.07 │ └──────────┴───────────────┴────────────────┘
The 30,952 sessions are the daily sum that lesson 03-06 already explained: 193 more than the month's 30,759 unique sessions, because those that cross midnight count on two days. For the same reason, the sessions with a purchase (3,736) do not match the 3,753 in the monthly funnel: a session split across two days may have the view on one and the purchase on the other, and then it does not complete the funnel on either. Neither figure is "the right one": they answer different definitions, and that is what lesson 04-05 will be about.
Common mistake: writing daily_funnel/*.parquet. In a partitioned table the files are one level further down, inside the date=... folders.
Exercise 3
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
SILVER = Path.home() / "novamarket" / "lake" / "silver"
spark = SparkSession.builder.master("local[*]").appName("exercise_0401").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
summary = (
spark.read.parquet(str(SILVER / "orders_complete"))
.groupBy("channel", "status")
.agg(F.count("*").alias("orders"),
F.round(F.avg("total_amount"), 2).alias("avg_amount"))
)
pdf = summary.toPandas() # 2 channels x 4 statuses = 8 rows
print(len(pdf), "rows on the driver")
print(pdf.pivot(index="status", columns="channel", values="orders"))
spark.stop()8 rows on the driver channel app web status delivered 6345 9612 pending 419 592 returned 388 613 shipped 834 1197
8 rows travel to the driver, not the 20,000 orders. If the lake held the real NovaMarket's 18 million orders a year, it would still be 8: the size of the result depends on the cardinality of the columns you group by, not on the source volume.
Conclusion
Analysis tools do not compete: they share out the work according to the volume of the data, the profile of whoever is asking and the latency they need. SQL engines (Trino and Presto, Spark SQL, the cloud data warehouse engines) are the gateway to massive data, and DuckDB offers that same SQL on Parquet on a single machine and with no infrastructure. Python with pandas or Polars, and R, provide flexibility and statistics on data that already fits in memory. Notebooks are the desk where everything comes together while you explore, and scripts are the home for whatever must be repeated. ML libraries and BI tools complete the map. You have answered the same question with Spark SQL, DuckDB and pandas, obtained identical figures at very different costs, and you take away the rule you will use for the rest of the module: aggregate big, analyse small, with toPandas() as the bridge and taking care not to cross it with too many rows.
Knowing which tool to ask with is only the beginning. Before building a model or a dashboard on some data, you need to get to know it: how it is distributed, which values are unusual, which columns move together and what limitations it suffers from. In the next lesson, Exploratory Data Analysis at Scale, you will learn to profile tables that do not fit in memory with Spark, using approximate statistics and sampling, and you will carry out a complete exploratory analysis of NovaMarket's orders and events.
