Contents/ Part XXV Β· Tools & Workflow/ Chapter 151

Python for Data Analysis

Python is the lingua franca of data work, and for one reason: a small, coherent stack of libraries takes you from a raw file all the way to a finished chart without ever leaving the language. This chapter is your working tour of that stack, paired with five hands-on notebooks so you learn it the only way that sticks, by running it.

⏱️ ~30 min read
🐍 5 Notebooks included
πŸ“Š Chapter 151

Ask a working data scientist what they open first, and the answer is almost always the same: a Python notebook. Not because Python is the fastest language or the most elegant, but because around it has grown the most complete ecosystem for analysis anywhere: arrays, dataframes, plots, statistics, and machine learning, all speaking to each other. Learn the handful of libraries in this chapter and you can load, clean, reshape, summarize, and visualize almost any dataset you meet.

🐍
Python for data analysis means a core stack: NumPy for fast numerical arrays, pandas for labeled tables (the DataFrame), and Matplotlib with seaborn for visualization, usually written in a Jupyter notebook that interleaves code, output, and prose.
🧰
This chapter comes with five notebooks, not one

Python for data analysis is too much ground to cover in a single companion, so this chapter is built around a five-notebook mini-course: Python foundations, NumPy, pandas essentials, reshaping and aggregation, and visualization. The sections below give you the map and the ideas; the notebooks give you the reps. Read a section, run its notebook, and change the code, that loop is the whole point.

1

The Python Data Stack

Python itself is a general-purpose language. What makes it the home of data analysis is a small set of libraries that layer cleanly on top of one another, each solving one problem and handing off to the next.

LibraryWhat it gives youWhere it fits
NumPyThe fast N-dimensional array and vectorized math. The numerical foundation. Almost everything else is built on it.
pandasThe labeled table (DataFrame) and Series, with loading, cleaning, joining, and grouping. The analyst's daily workhorse, where most of your time is spent.
MatplotlibComplete, low-level control over every element of a figure. The plotting engine underneath everything else.
seabornOne-line statistical charts with sensible defaults, built on Matplotlib. Fast, attractive exploratory visuals.
scikit-learnA uniform interface to machine-learning models (its own chapters in this book). Modeling, once the data is ready.
JupyterThe notebook: code, output, charts, and narrative in one document. The environment that ties it all together.

The design is deliberately layered. NumPy holds the numbers; pandas puts labels on them and adds table operations; Matplotlib draws them; seaborn makes the drawing easy; scikit-learn models them. You can drop down a layer whenever you need more control, which is why the stack scales from a five-line exploration to a production pipeline.

One stack, cleanly layered from numbers to insight JUPYTER NOTEBOOK · code, output, charts and prose in one document Matplotlib + seaborn visualization scikit-learn modeling (its own chapters) pandas · the labeled table (DataFrame) load, clean, filter, join, group, reshape NumPy · the fast N-dimensional array vectorized math, the numerical foundation for everything above insight raw numbers
Data flows upward: NumPy holds the raw numbers, pandas labels and reshapes them, and the top layer turns them into charts and models, all inside a Jupyter notebook. You can always drop a layer down for finer control.
2

NumPy: Think in Whole Arrays

NumPy contributes one deceptively simple idea that reshapes how you write code: put your numbers in an array and operate on the whole thing at once, rather than looping element by element. This is called vectorization, and it is both easier to read and, because the work runs in compiled code under the hood, often a hundred times faster than an equivalent Python loop.

total = quantity * price # one line multiplies every pair, no loop

Three companion ideas make arrays powerful. A boolean mask filters with a condition (prices[prices > 30]). Broadcasting stretches a smaller array to line up with a bigger one so you can combine different shapes without writing loops. And aggregations with an axis argument collapse an array in a chosen direction, axis=0 down the columns, axis=1 across the rows. Every one of these reflexes reappears in pandas, because pandas is built directly on NumPy. Notebook 2 drills all of them, including a timed race that shows the vectorized version running dozens of times faster than the loop.

3

pandas: The DataFrame Is the Workhorse

If you learn one thing from this chapter, learn pandas. A DataFrame is a table you can program: rows and columns like a spreadsheet, but with the full power of code behind every operation. The overwhelming majority of real analysis is a sequence of a few verbs on a DataFrame.

The verbWhat it doesTypical call
Load & inspectRead a file, then look before you leap. read_excel, head, info, describe
SelectPick columns and rows, by label or position. df["col"], df.loc[...], df.iloc[...]
FilterKeep rows matching a condition. df[df.revenue > 100]
TransformBuild new columns from existing ones. df["profit"] = df.rev - df.cost
Group & aggregateSplit into groups, summarize each. df.groupby("region").revenue.sum()
Join & reshapeCombine tables; pivot between wide and long. merge, pivot_table, melt

The one distinction worth pinning down early is loc versus iloc: loc selects by label, iloc by integer position. And whenever you process data in groups, remember the rule from the scaling chapter, you can sum and count per group but you cannot average the averages unless the groups are equal in size. Notebooks 3 and 4 walk the whole list, from a first head() through groupby, merge, pivot_table, dates, and method chaining, on the real dataset below.

Anatomy of a DataFrame index order_id region revenue rating 0 1 2 100001 North 45.00 5.0 100002 South 22.00 4.0 100003 North 110.00 NaN each column is a Series row labels one cell missing value df.loc[1, "revenue"] → 22.00 by LABEL df.iloc[1, 2] → 22.00 by POSITION
A DataFrame is columns (each a Series) sharing a row index. loc reaches a value by its labels, iloc by its integer position, and the two happen to agree here only because the index is the default 0, 1, 2. A missing rating shows up as NaN, which pandas skips in calculations unless you tell it not to.
πŸ”Ž
Always look before you analyze

The single most common beginner mistake is running statistics on data they have never actually looked at. Before any analysis, call head, info, and describe. Check the shape, the column types, and the count of missing values. Half of all “wrong” results are really a column read as text, a stray unit, or a pile of blanks that a five-second glance would have caught.

4

Real-World Example: From Raw File to Finished Chart

The five notebooks share one real dataset so you can watch a single file travel the entire stack: read with pandas, compute with NumPy, reshape with groupby and merge, and finish as a chart. It is a small online-store order log, chosen because it has a bit of everything: dates, categories, numbers, a join key, and some missing values.

Real dataset

Online store orders, 3,000 orders across 2024, in two sheets. The Orders sheet is the fact table: order_id, order_date, a product_id join key, the region and channel (web, mobile, store), quantity, discount_pct, the revenue in dollars, and a customer rating from 1 to 5 that is blank for about 6 percent of orders. The Products sheet is a small lookup table mapping each product_id to its name, category, unit cost, and list price, so you can join it in to compute profit.

Running the notebooks end to end tells a coherent little business story, and every number here comes straight from their executed output.

Notice the shape of that workflow: read, look, compute, group, join, plot, conclude. It is the same arc whether the file has three thousand rows or three hundred million. Master it on a dataset you can check by eye, and it carries everywhere.

The same seven-step arc, every dataset readread_excel lookhead, describe computeNumPy groupgroupby joinmerge plotmatplotlib concludethe answer pandas reads and reshapes, NumPy computes, Matplotlib and seaborn draw, and the notebook ties it together
The five notebooks walk this arc from left to right on one file. It scales unchanged: the tools and steps are the same at three thousand rows or three hundred million, which is exactly why it is worth learning well once.
🐍

The Five-Notebook Mini-Course

Work through these in order. Each is self-contained and runnable, building from the language itself up to a finished dashboard. Open them here or launch straight into Colab.

Notebook 1

Python Foundations

The language with no libraries: types, lists, dicts, tuples, sets, control flow, comprehensions, and functions, ending with a pure-Python analysis that shows why pandas exists.

Notebook 2

NumPy

Arrays and vectorization: creating arrays, the loop-versus-vector speed race, boolean masks, broadcasting, and axis-aware aggregations, finishing on the real revenue data.

Notebook 3

pandas Essentials

The DataFrame day to day: Series and DataFrames, loading and inspecting, selecting with loc and iloc, filtering, building columns, and handling missing data.

Notebook 4

Reshaping & Aggregating

Where analysis happens: groupby (split-apply-combine), merging tables, pivot_table, melt between wide and long, working with dates, and method chaining.

Notebook 5

Visualization

Turning tables into pictures: the anatomy of a Matplotlib figure, line, bar, histogram and scatter plots, one-line seaborn statistical charts, and a multi-panel dashboard.

Solutions

Challenge Solutions

Worked answers to the five practice challenges below, one per area, from a pure-Python summary through a plotted monthly trend.

Every notebook runs on numpy, pandas, matplotlib, seaborn, and openpyxl, all preinstalled on Colab.

5

Why Python Won Machine Learning & AI

Python is not just convenient for analysis; it is the default language of modern machine learning and AI. That was not inevitable, and understanding why it happened tells you what the ecosystem is really for.

ReasonWhat it means in practice
One array standard NumPy gave every library a common data structure. A pandas column, a scikit-learn input, and a deep-learning tensor are all arrays, so tools compose instead of fighting.
A consistent model API scikit-learn's fit/predict pattern became a convention the whole field copied, so trying a new model is a one-line change.
The deep-learning frameworks PyTorch and TensorFlow are Python-first. The research that defines modern AI is written, published, and shared as Python.
Glue, not speed The heavy math runs in compiled C, CUDA, or Rust underneath; Python is the readable layer that orchestrates it. You get C speed with scripting-language ergonomics.
Notebooks and community Jupyter made analysis shareable and reproducible, and a vast community means an answer, a package, or an example for almost anything.
Research note

The stack in this chapter is the visible tip of a deliberate design philosophy sometimes called “the SciPy ecosystem”: many small, interoperable libraries agreeing on NumPy's array as a common currency, rather than one monolithic tool. That agreement is why a dataframe flows into a plot flows into a model with no glue code, and it is the quiet reason Python, rather than a faster or more specialized language, became the place where data science and AI are actually done.

πŸŽ“ Key Takeaways

  • βœ“The stack is layered: NumPy arrays underneath, pandas tables on top, Matplotlib and seaborn for charts, scikit-learn for models, all inside a Jupyter notebook.
  • βœ“Vectorization is the NumPy mindset: operate on whole arrays at once for code that is shorter to write and often a hundred times faster to run.
  • βœ“The DataFrame is the workhorse: load, inspect, select, filter, transform, group, and join cover the large majority of real analysis.
  • βœ“loc selects by label, iloc by position, and you can sum or count per group but never average the averages of unequal groups.
  • βœ“Always look before you analyze: head, info, and describe catch the mis-typed column and the pile of blanks before they become wrong answers.
  • βœ“Match the chart to the question: a line for trend, bars for comparison, a histogram for shape, a scatter for relationship.
  • βœ“Python won AI on interoperability: a shared array standard and a consistent model API let tools compose, with the heavy math running in compiled code underneath.
6

Practice Challenges

Five exercises, one per notebook area, on the store-orders data. Full solutions are in the companion solutions notebook.

1

Pure-Python summary

Given a list of order values, compute the count, mean, and maximum using only built-ins and a comprehension, with no libraries.

Hint: sum(), len(), max(), and a list comprehension for the filter.
2

Vectorized NumPy

From the revenue array, report the share of revenue from orders over 100 dollars, and standardize the array to z-scores, all without a loop.

Hint: a boolean mask for the share, then (x - x.mean()) / x.std().
3

Filter with pandas

Keep web orders placed in the fourth quarter (October to December) and report how many there are and their total revenue.

Hint: combine conditions with &, and use order_date.dt.quarter.
4

Group with a join

Merge the products table, then report revenue and profit by category, sorted by profit.

Hint: merge on product_id, then groupby("category").agg(...).
5

Plot the trend

Plot 2024 revenue by month as a line chart and mark the peak month.

Hint: group by order_date.dt.to_period("M"), then plot and annotate the max.
πŸ““

Solutions notebook

All five challenges worked in code, one per area: a pure-Python summary, a vectorized NumPy share and z-score, a pandas quarter filter, a groupby with a merge, and a plotted, annotated monthly trend.

πŸ““ View Solutions β–Ά Open in Colab ⬇ GitHub
7

Quiz: Test Yourself

Eight questions on the stack, NumPy, pandas, and visualization. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved.

➑️
Up next

Python is one of two great open-source languages for statistics. R for Statistics turns to the other, built by statisticians for statisticians, and shows where each language shines. This is the start of the Tools & Workflow part, which surveys the practical craft: languages, software, databases, and the habits that make analysis reproducible. Browse the full Contents for what is published and what is on the way.