Chapter 1 — Python Essentials

Lists, Series, NumPy, SciPy, Matplotlib

Prof. Xuhu Wan

Chapter 1 · Introduction to Business Analytics

Python Essentials

Lists · pandas Series · NumPy · SciPy · Matplotlib

Prof. Xuhu Wan

ISOM, HKUST Business School · Wan Academy · 2026 Edition

What This Chapter Builds

The Python data-science stack evolved in layers, each solving a problem the previous one could not:

  • NumPy (2005) — fast contiguous arrays
  • pandas (2008) — labelled tabular data
  • SciPy (2001) — statistics, optimisation, integration
  • Matplotlib (2003) — plotting

By the end of this chapter, you can build a working restaurant performance analyser from scratch using all four.

Tip

Why this matters. Netflix’s recommender, Foodpanda’s dispatch system, every operations team’s analytics pipeline — all run on these same four libraries.

Roadmap

Section Concept Tool
1 Lists & indexing Python built-in
2 List comprehensions Python built-in
3 pandas Series pandas
4 Descriptive statistics pandas
5 NumPy arrays numpy
6 Random simulation numpy.random
7 Plotting matplotlib
8 Probability & SLA thresholds scipy.stats

§1 · Lists

§1 — Lists

Your first data container.

Lists: Indexing

Note

Positive indices count from the start (0, 1, 2…). Negative indices count from the end (-1, -2…). Slicing is half-open: [1:3] returns positions 1 and 2.

Indexing Visualised

§2 · List Comprehensions

§2 — List Comprehensions

Doing more with one line.

Three Patterns

Transform every item

deliveries = [22, 35, 18, 41, 27]   # minutes
plus_buffer = [t + 5 for t in deliveries]
# [27, 40, 23, 46, 32]

Filter — keep some items

late = [t for t in deliveries if t > 30]
# [35, 41]

Conditional value — every item gets a label

deliveries = [22, 35, 18, 41, 27]
sla = ["On time" if t <= 30 else "Late"
       for t in deliveries]
# ['On time', 'Late', 'On time', 'Late', 'On time']

Tip

The conditional value comes before for. The filter condition comes after for. Don’t confuse them.

§3 · pandas Series

§3 — pandas Series

Labelled 1D arrays with built-in statistics.

A Series is a Labelled List

Note

A pandas Series = a NumPy array + an index (the labels) + a name (the column header). Each row keeps its label through every operation.

Descriptive Statistics in One Call

count     5.0
mean    138.8
std      23.6
min     118.0
25%     125.0
50%     132.0
75%     141.0
max     178.0

Important

.describe() gives the 8-number summary in one line. It is the single most useful first-look method for any quantitative column.

The ddof=1 vs ddof=0 Trap

pandas defaults to sample standard deviation (divide by n−1);
NumPy defaults to population standard deviation (divide by n).

Warning

Rule of thumb. Leave pandas’ .std() at its default — sample std (ddof=1) is what every statistics textbook and Excel’s STDEV.S use.

§4 · NumPy

§4 — NumPy Arrays

Vectorised math at C speed.

Lists vs NumPy: The Single Bug Everyone Hits

[100, 102, 98, 105, 101, 100, 102, 98, 105, 101]
[200 204 196 210 202]

Important

A Python list * operator means concatenate. A NumPy array * operator means element-wise multiplication. Mistaking them is the most common bug when moving from lists to NumPy.

Why NumPy Is 10–100× Faster

Note

NumPy delegates math to BLAS/LAPACK — the same compiled C/Fortran libraries that run MATLAB and Bloomberg risk engines. The Python interpreter never touches the inner loop.

Simulating Daily Step Counts

A 100-day simulation in three lines: draw daily steps from N(8500, 1500²), summarise, count goal-hit days.

Tip

Replace the seed(42) line and re-run to see a different person’s step pattern. Wearable-device teams run thousands of such simulations to tune daily-goal notifications.

§5 · SciPy Stats

§5 — SciPy Stats

Distributions, CDFs, and service-level thresholds.

CDF and PPF — Two Halves of One Idea

CDF: value → probability

\[P(X < x) = \text{cdf}(x)\]

stats.norm.cdf(10, loc=8, scale=2)
# 0.841

84.1 % of outcomes from N(8, 2²) fall below 10.

PPF: probability → value

\[x \text{ such that } P(X < x) = p\]

stats.norm.ppf(0.05, loc=8, scale=2)
# 4.71

5 % of outcomes fall below 4.71.

The PPF is the mathematical inverse of the CDF. Together they let you answer every probability question about a normal random variable.

CDF and PPF Visualised

Delivery-Time SLA = PPF of the Right Tail

Important

95 % SLA = “95 % of orders arrive within this time.” A single number every logistics ops team reports daily, used to staff couriers and trigger alerts.

§6 · Putting It Together

§6 — Mini Project

Restaurant performance analyser in 20 lines.

A Working Restaurant Analyser

Tip

Twenty lines combine everything you’ve seen: lists, comprehensions, zip, f-strings, pd.Series, and a managerial classification rule. The same logical pipeline a junior analyst at a restaurant chain assembles for a weekly menu review.

Same Methods, Different Context: K-pop Streams

Same descriptive statistics you just learned — now applied to the music industry rather than equity prices.

Working with an AI Copilot

An AI copilot suggests numpy.std(prices) to compute volatility. The code runs, but np.std defaults to ddof=0 (population) — you almost certainly wanted ddof=1 (sample). The code is correct; the assumption is wrong, and the AI will not flag it.

  1. Prompt the AI to explain its choice, not just produce code — ask why this function, why these arguments.
  2. For any statistic, ask which ddof, axis, and skipna defaults it used, and whether they match your data.
  3. When in doubt, compute the same thing two ways (pandas vs NumPy, or by hand) and check they agree.

Mistakes Library: UK 2020 A-level Algorithm

Warning

Summer 2020. Covid forced OfQual (UK exam regulator) to cancel in-person A-level exams. They replaced them with a statistical algorithm that combined each teacher’s predicted grade with the school’s historical grade distribution. The algorithm downgraded roughly 40% of teacher predictions, and the damage fell hardest on disadvantaged schools — because those schools had lower historical means, every individual student was pulled down toward that mean, regardless of their own ability.

Lesson: descriptive statistics computed at the group level (a school’s mean, a sector’s volatility) cannot fairly score individuals. Aggregates describe distributions, not people. Always ask: what is the unit of analysis, and does my statistic respect it?

Decision Memo — Should the Label Push a Comeback?

You are a junior analyst at JYP Entertainment. The 20-day stream series above is for a debut track. A&R wants to know whether to spend extra marketing budget in week 3.

To: JYP Entertainment, A&R Team From: , junior analyst Subject: Hold the additional comeback push in week 3 Date: 2026-05-15

Recommendation: Do not allocate the extra marketing budget — track is within expected variance.

Evidence: - 20-day mean: 11.6 M streams/day; sample std: 2.5 M. - 95% VaR-style lower band ≈ 6.7 M/day → tail risk acceptable. - 20-day trend ≈ flat (+0.05 M/day, not significant).

Caveats: - Assumes future days drawn from the same distribution. - 20-day window short; weekly seasonality may dominate.

Next step: Re-run with 60 days plus ARIMA before any budget decision.

Chapter Summary

Concept Tool Use
Ordered collection list Menu items, daily logs
Concise transform comprehension On-time / Late labels
Labelled 1D pd.Series Daily check-ins, streams
Fast vector math np.array Monte Carlo, step counts
Probability scipy.stats.norm SLA thresholds, hypothesis tests
Charts matplotlib Histograms, lines

Next: Chapter 2 — DataFrames (Series side-by-side; the actual workhorse of every analytical pipeline).

Discussion Questions

  1. Why does pandas default std() to n−1 while NumPy defaults to n? What would happen if an ops team computed a 95 % SLA using n instead of n−1 on a small sample?
  2. When would you choose a list comprehension over an explicit for-loop? When would the for-loop be more readable?
  3. The SLA example used a normal distribution for delivery times. List two ways real delivery-time distributions deviate from the normal assumption, and why that matters for the threshold you set.
  4. Walk through the restaurant analyser: what is the shape of each intermediate list, and which line would you change first if a fifth dish were added?