Marc now knows which tools to ask his questions with. Before building a model or a dashboard, however, a good analyst spends time on something less glamorous: getting to know the data. What does a normal order amount to? Are there absurd values? Which columns move together? Do people buy more on Mondays? Anyone who skips this step ends up discovering the quirks in the data after they have already presented a wrong figure.
This reconnaissance of the terrain is called exploratory data analysis (EDA). In this lesson you will learn how to do it when the data does not fit in memory: which statistics to ask Spark for, why approximate answers are accepted at scale, when you can trust a sample and how to write down what you have learnt. You will practise with a complete EDA of NovaMarket's orders and events, which has a surprise or two in store.
What EDA is and what changes at scale
EDA is the systematic examination of a dataset, before using it for anything, in order to understand its structure, its quality and its patterns. It does not start from a hypothesis to be confirmed: its aim is precisely to discover which questions are worth asking and what should not be trusted.
It should not be confused with the cleaning you did in Modules 2 and 3. There you corrected known defects (duplicates, types, empty amounts). EDA works on the already clean data in the silver zone and answers a different question: not "is it right?", but "what is it like?".
On a laptop, with pandas, EDA is almost a reflex: you load the file and ask for df.describe() and a couple of charts. With massive data, four things change:
| With data that fits in memory | With massive data |
|---|---|
| You look at the whole table | You cannot look at it: you summarise it |
| Every statistic is instantaneous | Every statistic is a job; it pays to ask for several in a single pass |
| Median and distinct counts are exact | Calculating them exactly requires sorting or shuffling all the data: approximations are used |
| Every point is plotted | Aggregates or samples are plotted |
The rule from the previous lesson still holds: aggregate big, analyse small. Everything you do here consists of Spark aggregations whose result, a few rows long, can then be read, saved or moved to pandas.
Create ~/novamarket/eda.py with the lesson's skeleton; you will add snippets before spark.stop() as you go:
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("eda").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.parquet(str(SILVER / "orders_complete"))
events = spark.read.parquet(str(SILVER / "web_events"))
# ... snippets from the lesson ...
spark.stop()First look: shape, statistics, nulls and cardinalities
Shape and basic statistics
The first thing is to know what you have in front of you: orders.printSchema() for columns and types, orders.count() for the rows (20,000) and orders.show(3) to see real data. Then, the statistics for the numeric columns:
+-------+------------------+ |summary| total_amount| +-------+------------------+ | count| 20000| | mean|1677.5384215000124| | stddev| 1244.749539038338| | min| 11.26| | 25%| 753.3| | 50%| 1406.73| | 75%| 2295.45| | max| 12631.7| +-------+------------------+
summary()calculates the count, mean, standard deviation, minimum, maximum and the 25th, 50th and 75th percentiles. Its siblingdescribe()does the same without the percentiles.countcounts the non-null values: the fact that it matches the 20,000 rows confirms that no amount is missing.- The mean (€1,677.54) is considerably higher than the median (the 50th percentile: €1,406.73). This is the first clue about the shape of the distribution: there is a tail of expensive orders pulling the mean upwards.
- The maximum (€12,631.70) is nine times the median. It will need looking at.
Always select the columns you are interested in: summary() on a 200-column table calculates statistics for all of them.
Nulls per column
To count the nulls in every column in a single pass over the data, you build a list of aggregations, one per column:
def nulls(df):
return df.select([
F.sum(F.col(c).isNull().cast("int")).alias(c) for c in df.columns
])
nulls(orders).show()
nulls(events).show()F.col(c).isNull() is true or false; cast to an integer it is 1 or 0, and its sum is the number of nulls. The list comprehension generates that expression for each column, and Spark evaluates them all while reading the data only once.
+--------+-----------+----------+------------+------+-------+--------------+ |order_id|customer_id|order_date|total_amount|status|channel|amount_rebuilt| +--------+-----------+----------+------------+------+-------+--------------+ | 0| 0| 0| 0| 0| 0| 0| +--------+-----------+----------+------------+------+-------+--------------+ +-----------+------+--------+----------+----------+----------+----------+----+ |customer_id|device|event_id|event_time|event_type|product_id|session_id|date| +-----------+------+--------+----------+----------+----------+----------+----+ | 60684| 1000| 0| 0| 0| 29920| 0| 0| +-----------+------+--------+----------+----------+----------+----------+----+
The orders are complete, thanks to the rebuilding in lesson 03-03. In the events there are three columns with nulls, and each one tells a different story:
customer_id: 60,684 nulls, 30.3%. This is not a defect: they are the anonymous visitors.product_id: 29,920 nulls, exactly the number of searches. Not a defect either: a search has no product.device: 1,000 nulls, 0.5%. This one really is a capture defect, a small one.
The lesson it leaves you with: a null is not always an error. Before filling it in or discarding it, you need to understand what it means.
Cardinalities
The cardinality of a column is its number of distinct values. It says a lot about the column's role: a cardinality equal to the number of rows points to an identifier; a very low one, to a category to group by.
def cardinalities(df):
return df.select([F.approx_count_distinct(c).alias(c) for c in df.columns])
cardinalities(orders).show()
cardinalities(events).show()+--------+-----------+----------+------------+------+-------+--------------+ |order_id|customer_id|order_date|total_amount|status|channel|amount_rebuilt| +--------+-----------+----------+------------+------+-------+--------------+ | 18595| 1026| 21465| 15869| 4| 2| 2| +--------+-----------+----------+------------+------+-------+--------------+ +-----------+------+--------+----------+----------+----------+----------+----+ |customer_id|device|event_id|event_time|event_type|product_id|session_id|date| +-----------+------+--------+----------+----------+----------+----------+----+ | 1026| 3| 197864| 202347| 4| 195| 30824| 32| +-----------+------+--------+----------+----------+----------+----------+----+
Something does not add up, and it is deliberate. You know there are 20,000 distinct order_id values, and here 18,595 appear. There are 1,000 customers and it says 1,026. And the events would have more distinct timestamps (202,347) than rows (200,000)! This is not a bug: approx_count_distinct, which you met in lesson 03-03, returns an estimate, with a typical relative error of 5% by default, which can be exceeded in some cases, as with order_id.
For the purpose of this step it does not matter: what you are after is the order of magnitude. order_id and event_id are identifiers; status, channel, device and event_type are categories; customer_id is around a thousand. The second parameter adjusts the precision, at the cost of more memory: F.approx_count_distinct("order_id", 0.01) returns 19,972.
Why not ask for the exact value with countDistinct? Because it is expensive, and all the more so the more columns you ask for at once. While this lesson was being prepared, running seven countDistinct in a single query on the events exhausted Spark's memory in local mode, with only 200,000 rows; the approximate version takes an instant. The section on approximate algorithms explains why.
For low-cardinality columns, the next step is the frequency table:
total = orders.count()
for column in ("status", "channel"):
(orders.groupBy(column).agg(F.count("*").alias("n"))
.withColumn("pct", F.round(100 * F.col("n") / total, 1))
.orderBy(F.desc("n")).show())+---------+-----+----+ | status| n| pct| +---------+-----+----+ |delivered|15957|79.8| | shipped| 2031|10.2| | pending| 1011| 5.1| | returned| 1001| 5.0| +---------+-----+----+
By channel, 60.1% of orders come through the web (12,014) and 39.9% through the app (7,986).
Distributions: percentiles, histograms and outliers
Approximate percentiles
The mean is a poor summary of a skewed distribution. Percentiles describe it better: the 95th percentile is the value below which 95% of orders fall. Spark calculates them in two equivalent ways:
# As a DataFrame method: returns a Python list
quantiles = orders.approxQuantile("total_amount", [0.25, 0.5, 0.75], 0.01)
print(quantiles)
# As an aggregate function: can be combined with groupBy
orders.select(
F.percentile_approx("total_amount", [0.5, 0.95, 0.99]).alias("p50_p95_p99")
).show(truncate=False)
orders.groupBy("channel").agg(
F.percentile_approx("total_amount", 0.5).alias("median"),
F.round(F.avg("total_amount"), 2).alias("mean"),
).show()[728.97, 1406.42, 2268.9] +--------------------------+ |p50_p95_p99 | +--------------------------+ |[1406.73, 4092.4, 5768.48]| +--------------------------+ +-------+-------+-------+ |channel| median| mean| +-------+-------+-------+ | app|1396.06|1677.33| | web|1411.52|1677.68| +-------+-------+-------+
approxQuantile(column, probabilities, error): the third argument is the permitted relative error. With0.01, the value returned for the median is guaranteed to lie between the true 49th and 51st percentiles. With0.0the calculation is exact (and expensive): it would give 753.43, 1,406.81 and 2,295.58.percentile_approxis an ordinary aggregate function, which is why it acceptsgroupBy. Its default precision is finer, hence the small differences from the previous line.- Business reading: 95% of orders come to less than €4,100, and 1% exceed €5,768. The web and the app have almost identical means: the channel has no influence on the amount.
Binned histogram calculated in Spark
A histogram divides the range of values into equal intervals, the bins, and counts how many rows fall into each one. With massive data you do not send the values to the charting tool: the counting is done in Spark and only the bins travel.
WIDTH = 500
histogram = (
orders
.withColumn("bin", (F.floor(F.col("total_amount") / WIDTH) * WIDTH).cast("int"))
.groupBy("bin").count()
.orderBy("bin")
)
h = histogram.toPandas() # one row per bin: it is small
for bin_start, n in zip(h["bin"], h["count"]):
if bin_start < 6000:
print(f"{bin_start:>6} | {'#' * round(60 * n / h['count'].max())} {n}")F.floor(amount / 500) * 500 turns each amount into the start of its bin: €1,230 becomes 1,000; €2,780, 2,500. After that, a groupBy is all it takes. The result has around twenty rows, so toPandas() is safe, and a simple print gives you a text histogram:
0 | ################################################ 3076 500 | ############################################################ 3818 1000 | ########################################################### 3778 1500 | ############################################## 2944 2000 | ################################## 2175 2500 | ####################### 1493 3000 | ################ 1009 3500 | ########## 616 4000 | ####### 418 4500 | #### 257 5000 | ## 149 5500 | ## 102
There is the shape that the mean and the median hinted at: a right-skewed distribution, with most orders between €500 and €1,500 and a long tail of expensive orders. It is the typical shape of almost any amount variable. In lesson 04-04 you will turn this same table into a proper chart.
Outliers: the IQR rule
An outlier is a value that lies a long way from the rest. The most widely used rule for flagging them is based on the interquartile range (IQR), the distance between the 25th percentile (Q1) and the 75th (Q3): anything below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR is considered an outlier. Unlike rules based on the mean and standard deviation, it is barely affected by the outliers themselves.
q1, q3 = orders.approxQuantile("total_amount", [0.25, 0.75], 0.0)
iqr = q3 - q1
upper_limit = q3 + 1.5 * iqr
outliers = orders.where(F.col("total_amount") > upper_limit)
print(f"Q1={q1} Q3={q3} IQR={iqr:.2f} upper limit={upper_limit:.2f}")
print("Outlier orders:", outliers.count())
outliers.agg(F.round(F.sum("total_amount"), 2).alias("outlier_sales")).show()Q1=753.43 Q3=2295.58 IQR=1542.15 upper limit=4608.81 Outlier orders: 605 +-------------+ |outlier_sales| +-------------+ | 3398810.84| +-------------+
The lower limit would be negative, so there are no outliers at the bottom. At the top there are 605 orders, 3%, adding up to €3.4 million: 10% of sales. Two conclusions:
- An outlier is not the same as an error. These orders are legitimate, with several televisions or computers. Removing them "because they spoil the mean" would mean throwing away 10% of turnover. The rule flags candidates for review; the decision is a business one.
- With skewed distributions, the IQR rule flags many values. It is not pointing out 605 anomalies, but confirming that the tail is long. To describe the typical order, use the median.
Approximate algorithms: why an almost exact answer is enough
You have used two "approximate" functions. It is worth understanding why they exist, because they are one of the most characteristic ideas in Big Data.
The problem. To count exactly how many distinct values there are, something has to remember all the ones it has already seen. With 2 million customers that is not serious; with billions of event identifiers, that list does not fit in an executor's memory, and on top of that the data has to be shuffled between machines so that equal values meet. The same happens with the exact median: it requires sorting the whole column.
HyperLogLog, the algorithm behind approx_count_distinct, avoids remembering the values. The intuition is that of tossing coins. If someone tells you that their longest run of consecutive heads was 3, you will assume they tossed only a few times; if they tell you it was 20, they will have tossed around a million times, because a run like that happens once in every 2²⁰. The longest run lets you estimate the number of tosses without having counted them.
HyperLogLog does the same with data: it turns each value into a random-looking number (a hash) and records the longest run of zeros that any of them starts with. A repeated value always produces the same hash, so it does not alter the result: that is why it counts distinct values. To stop a lucky run from ruining the estimate, it spreads the values across thousands of groups and averages them. The result:
- It takes up a few kilobytes, whether there are a thousand values or a trillion.
- It reads the data only once, without sorting.
- The summaries of two partitions can be merged, which makes it ideal for distributed computing.
- In exchange, it makes an error of a small percentage, which can be tuned.
Approximate quantiles follow a similar idea: instead of sorting all the values, each partition keeps a compact summary (a sketch) with a handful of representative values and the approximate position they occupy. The summaries are merged, and the percentile is read from the final summary with a bounded error: the parameter you passed to approxQuantile.
Is it acceptable not to be exact? For exploring and for deciding, almost always. Whether NovaMarket has 30,759 sessions or 30,824 does not change any decision. Exactness does matter in accounting, invoicing and any figure with legal weight: there you use the exact calculation and pay its cost.
Relationships and time: correlations and temporal patterns
Correlations
Pearson's correlation coefficient measures, between −1 and 1, how much two numeric columns move together: close to 1, they rise together; close to −1, one rises when the other falls; close to 0, there is no linear relationship. To have something to relate, each order is given its number of lines and units:
lines = spark.read.parquet(str(SILVER / "order_lines"))
by_order = (
lines.groupBy("order_id")
.agg(F.count("*").alias("num_lines"), F.sum("quantity").alias("units"))
.join(orders, "order_id")
.withColumn("hour", F.hour("order_date"))
)
for column in ("num_lines", "units", "hour"):
print(column, round(by_order.stat.corr(column, "total_amount"), 3))Units and amount are clearly related (0.67), as you would expect. The time of the order bears no relationship at all to the amount (−0.009).
Two warnings that never go out of date. Correlation does not imply causation: two columns moving together does not tell you which causes which, or whether both depend on a third. And Pearson only measures linear relationships: a 0 does not rule out other kinds of dependence.
Temporal analysis
Almost every business has a rhythm: peak hours, weekends, campaigns. You look for it by grouping by components of the date:
(orders.groupBy(F.dayofweek("order_date").alias("weekday"))
.agg(F.count("*").alias("orders"),
F.round(F.avg("total_amount"), 2).alias("avg_amount"))
.orderBy("weekday").show())
by_hour = orders.groupBy(F.hour("order_date").alias("hour")).count()
by_hour.agg(F.min("count").alias("min_hour"), F.max("count").alias("max_hour")).show()F.dayofweek returns 1 for Sunday and 7 for Saturday; F.hour, the hour from 0 to 23.
+-------+------+----------+ |weekday|orders|avg_amount| +-------+------+----------+ | 1| 2846| 1663.62| | 2| 2833| 1699.52| | 3| 2961| 1678.5| | 4| 2761| 1694.88| | 5| 2840| 1665.15| | 6| 2841| 1671.13| | 7| 2918| 1670.69| +-------+------+----------+ +--------+--------+ |min_hour|max_hour| +--------+--------+ | 773| 868| +--------+--------+
And here comes the most important finding of the EDA: there is no pattern. Every day of the week has practically the same number of orders, and the quietest hour (773 orders) and the busiest (868) are barely distinguishable: people buy just as much at four in the morning as at eight in the evening. The same happens by month: between 3,083 and 3,474 orders, and the minimum is February, which has fewer days.
No real shop behaves like this. You have just rediscovered with data the limitation that lesson 01-05 announced: the practice data was generated at random, with no seasonality. This is exactly the kind of thing an EDA must bring to light before someone tries, for example, to train a demand forecast by day of the week on it.
Sampling
Another way of reducing the data is to keep a part chosen at random: a sample.
sample = orders.sample(fraction=0.1, seed=42)
print(sample.count())
sample.agg(F.round(F.avg("total_amount"), 2).alias("mean"),
F.max("total_amount").alias("maximum"),
F.countDistinct("customer_id").alias("customers")).show()fraction=0.1is the probability of each row being included in the sample. It does not guarantee exactly 10%: here you get 2,035 rows, not 2,000.seed=42fixes the random generator's seed so that the sample is reproducible.
| Statistic | Full table | 10% sample | Reliable? |
|---|---|---|---|
| Mean amount | €1,677.54 | €1,715.26 | Yes: 2% error |
| Breakdown by status (returned) | 5.0% | 5.2% | Yes |
| Maximum | €12,631.70 | €8,773.18 | No |
| Distinct customers | 1,000 | 864 | No (and multiplying by 10 does not fix it) |
From this comes the criterion:
- A sample is reliable for means, proportions and the general shape of the distribution, provided it is random and contains enough rows from the group of interest. The precision depends on the absolute size of the sample, not the percentage: 10,000 well-chosen rows estimate a proportion with an error of around one point, whether they come from a million rows or a billion.
- It is not reliable for extremes (maximums, minimums), rare events (fraud: 32 customers out of a thousand), distinct value counts or exact totals.
- A convenience sample is not random.
limit(1000)or "the first file" return contiguous rows, perhaps all from the same hour. And be careful when sampling rows from related tables: a sample of events leaves sessions incomplete; to study sessions you must sample sessions and bring in all their events.
Stratified sampling
If a group is small, a simple sample leaves it with very few rows. Stratified sampling sets a different fraction for each group (stratum). To study returns, which are only 5%:
fractions = {"delivered": 0.05, "shipped": 0.05, "pending": 0.05, "returned": 0.5}
stratified = orders.sampleBy("status", fractions=fractions, seed=42)
stratified.groupBy("status").count().orderBy("status").show()+---------+-----+ | status|count| +---------+-----+ |delivered| 826| | pending| 52| | returned| 509| | shipped| 102| +---------+-----+
Now there are 509 returns to analyse, instead of the hundred or so in a simple sample. The downside: this sample no longer represents the whole (returned orders make up a third of it), so it cannot be used to calculate overall means without weighting. You will come across this technique again in lesson 04-03, when dealing with imbalanced classes.
EDA of the web events
Applied to silver/web_events (200,000 rows), the same routine gives these frequencies:
for column in ("event_type", "device"):
events.groupBy(column).count().orderBy(F.desc("count")).show()+------------+------+ +-------+------+ | event_type| count| | device| count| +------------+------+ +-------+------+ |product_view|140105| | mobile|118689| | search| 29920| |desktop| 63689| | add_to_cart| 21905| | tablet| 16622| | purchase| 8070| | NULL| 1000| +------------+------+ +-------+------+
(The two tables are shown side by side to save space.) 70% of events are product views, and mobile accounts for 59% of activity. But an individual event says little: the natural unit of analysis is the session. You build a table with one row per session:
sessions = events.groupBy("session_id").agg(
F.count("*").alias("events"),
F.max(F.col("customer_id").isNull()).alias("anonymous"),
((F.max("event_time").cast("long") - F.min("event_time").cast("long")) / 60)
.alias("duration_min"),
)
sessions.select("events", "duration_min").summary("min", "50%", "max").show()
sessions.groupBy("anonymous").count().show()
sessions.groupBy("events").count().orderBy("events").show(12)Casting a timestamp to long gives the seconds elapsed since 1970; the difference between the last and the first, divided by 60, is the duration in minutes.
+-------+------+------------------+ +---------+-----+ |summary|events| duration_min| |anonymous|count| +-------+------+------------------+ +---------+-----+ | min| 1| 0.0| | true| 9257| | 50%| 6| 8.216666666666667| | false|21502| | max| 12|27.416666666666668| +---------+-----+ +-------+------+------------------+
The third table has twelve rows, one per session size, all with between 2,496 and 2,654 sessions.
Findings:
- 9,257 of the 30,759 sessions are anonymous: 30.1%. You rediscover the 30% of unidentified visitors. This has a serious consequence for analysis: any "per customer" study of browsing ignores almost a third of the traffic.
- Sessions have between 1 and 12 events, and every size is equally frequent (about 2,500 sessions each). Such a flat distribution, with such a clean cap, does not exist in real browsing, where single-event sessions abound and there is a long tail. It is another fingerprint of the data generator.
- The purchase rate does not depend on anything. 4.0% of anonymous visitors' events are purchases, the same as the 4.0% for identified customers; and the same is true by device. Make a note of it: it will explain what happens in the next lesson.
- There is no hourly rhythm: between 7,865 and 8,747 events in each hour of the day.
There is one instructive trap left. The count by day of the week seems, at last, to show a pattern:
+-------+-----+ |weekday|count| +-------+-----+ | 1|26693| | 2|34057| | 3|33809| | 4|26118| | 5|26363| | 6|26583| | 7|26377| +-------+-----+
Is there 28% more activity on Mondays (2) and Tuesdays (3)? No: June 2026 has five Mondays and five Tuesdays, and four of each of the other days. Divided by the number of days, that comes to about 6,800 events per Monday and about 6,700 per Sunday. Comparing totals for periods with different numbers of days is one of the most common mistakes in temporal analysis; the correct approach is to compare daily averages.
And one last detail: the table has 31 date partitions (the cardinality estimate said 32) for a 30-day month. The last one, 2026-07-01, contains 47 events: they are the end of sessions that started on the night of 30 June. It is not an error, but a daily chart would show a collapse on the last day if it were not excluded.
EDA report template
An EDA that stays in the head of whoever did it is of no use to anyone. Its deliverable is a short report that accompanies the dataset. This template, filled in with the orders, serves as a model:
EDA REPORT — silver/orders_complete Author: Marc Date: 2026-07-02
1. SCOPE
What it is: one order per row. Period: 2026-01-01 to 2026-06-30. Rows: 20,000. Columns: 7.
2. QUALITY
Nulls: none. Duplicate order_id values: none.
200 amounts rebuilt from the lines (column amount_rebuilt).
3. VARIABLES
total_amount: median €1,407, mean €1,678, p95 €4,092, max €12,632.
Right-skewed.
status: delivered 79.8%, shipped 10.2%, pending 5.1%, returned 5.0%.
channel: web 60.1%, app 39.9%.
customer_id: 1,000 customers, between 7 and 36 orders each.
4. RELATIONSHIPS
Amount and units: correlation 0.67. Channel and hour have no influence on the amount.
5. TEMPORAL PATTERNS
No seasonality by hour, day of the week or month (synthetic data).
6. OUTLIERS
605 orders (3%) above €4,609 (IQR rule); they account for 10% of sales.
They are legitimate: do not remove.
7. LIMITATIONS AND WARNINGS
Not suitable for seasonal demand forecasting.
The orders do not tally with the `purchase` events in web_events.
8. OPEN QUESTIONS AND NEXT STEPS
What sets the highest-spending customers apart? -> segmentation (lesson 04-03).The eight sections are valid for any table. The seventh is the most valuable and the one most often forgotten: it tells whoever comes next what this data is not good for.
Common Mistakes and Tips
- Skipping the EDA "because the data is already clean". Clean does not mean known. The lack of seasonality is not a quality defect and yet it invalidates entire analyses.
- Asking for exact statistics out of habit.
countDistinctand the exact median on billions of rows can take hours or exhaust memory. Explore with approximations. - Taking an estimate for an exact figure. "32 dates in a month" is the sign that you are reading an approximation. If the figure is going into an official report, calculate it exactly.
- Launching one job per statistic. Group the aggregations into a single
selectoragg: one pass instead of twenty. And if you are going to explore a table a lot, considercache()(lesson 03-04). - Describing a skewed distribution with the mean. Always accompany it with the median and some high percentile.
- Deleting outliers without looking at them. First you understand them; then you decide.
- Using
limit()as if it were a sample. It is not random. - Extrapolating from a sample what cannot be extrapolated: maximums, distinct values, rare events.
- Comparing periods of different lengths. Months of 28 and 31 days, or weeks with five Mondays: compare daily averages.
- Tip: before accepting a striking pattern, look for the boring explanation (the calendar, a change in data capture, a duplicate). It is usually the right one.
Exercises
Exercise 1: profiling a table
Profile silver/customers: number of rows, nulls per column, approximate cardinality of each column and the five provinces with the most customers. Which known defect reappears? What strikes you about the cardinalities?
Exercise 2: what a sample can tell you
Take a 5% sample of silver/web_events with seed 7. Use it to estimate (a) the percentage of events from mobile and (b) the number of distinct sessions in the month. Compare with the real values (59.3% and 30,759) and explain the result.
Exercise 3: outliers in the sessions
Apply the IQR rule to the number of events per session. How many outlier sessions are there? What does the result tell you about the data?
Solutions
Exercise 1
customers = spark.read.parquet(str(SILVER / "customers"))
print(customers.count())
nulls(customers).show()
cardinalities(customers).show()
customers.groupBy("province").count().orderBy(F.desc("count")).show(5)Result: 1,000 rows; 20 nulls in province and none in the other columns; approximate cardinalities of 1,026 (customer_id), 394 (name), 14 (province) and 726 (signup_date); and the top five provinces are Valencia (213), Madrid (193), Barcelona (155), Alicante (80) and Seville (62).
The 20 customers with no province from lesson 01-05 reappear; groupBy would group them into a NULL row. In the cardinalities, name stands out: some 394 distinct values for 1,000 customers, in other words many repeated names. The name cannot be used to identify a customer; that is what customer_id is for (whose "1,026" values are, once again, the estimate of the real 1,000). There are 14 provinces, with Valencia at the top, as befits the head office.
Exercise 2
m = events.sample(fraction=0.05, seed=7)
n = m.count()
(m.groupBy("device").agg(F.count("*").alias("n"))
.withColumn("pct", F.round(100 * F.col("n") / n, 1))
.orderBy(F.desc("n")).show())
sample_sessions = m.select(F.countDistinct("session_id")).first()[0]
print(n, sample_sessions, sample_sessions * 20)The sample has 9,980 events: mobile 59.3%, desktop 31.8%, tablet 8.4% and nulls 0.5%. The last line prints 9980 8374 167480.
(a) The 9,980-event sample estimates 59.3% for mobile: spot on. Proportions are estimated well with a few thousand rows.
(b) There are 8,374 distinct sessions in the sample. Multiplying by 20 would give 167,480, more than five times the real value; and not multiplying falls short at a quarter of it. Neither operation works: since each session has several events, many sessions appear in the sample with a single event and others do not appear at all. Distinct value counts cannot be extrapolated from a sample of rows; they are calculated on the full data with approx_count_distinct.
Exercise 3
by_session = events.groupBy("session_id").agg(F.count("*").alias("events"))
q1, q3 = by_session.approxQuantile("events", [0.25, 0.75], 0.0)
upper_limit = q3 + 1.5 * (q3 - q1)
print(q1, q3, upper_limit, by_session.where(F.col("events") > upper_limit).count())None. Q1 = 3 and Q3 = 10, so the limit is 20.5, and the longest session has 12 events. In real browsing data there are always outsized sessions: bots, tabs left open for hours, internal tests. Having not a single outlier is, paradoxically, an anomaly: it gives away data generated with a fixed cap. An EDA also serves to make you suspicious of data that is too tidy.
Conclusion
Exploratory analysis is the reconnaissance that precedes any serious analysis. At scale you do not look at the table: you summarise it, with aggregations that Spark calculates in a few passes. You have profiled a table with summary, counted the nulls and cardinalities of every column at once, described distributions with approximate percentiles and binned histograms calculated in Spark, flagged outliers with the IQR rule, and looked for correlations and temporal patterns. You know why algorithms such as HyperLogLog trade a little accuracy for an enormous gain in efficiency, and when a sample, simple or stratified, is reliable and when it misleads.
NovaMarket's EDA leaves findings that shape everything that follows: the amounts are skewed, with 3% of orders contributing 10% of sales; 30% of sessions are anonymous; and, above all, the practice data has no seasonality and no relationship whatsoever between a session's behaviour and its purchase. With that knowledge, you can take the next step with your eyes open. In the next lesson, Machine Learning and Big Data, you will use this same data to train models with Spark MLlib: you will segment customers according to their purchasing behaviour and try to predict which sessions end in a purchase. What you have just discovered will help you to interpret, honestly, what those models achieve and what they do not.
