PDA·01 · Chapter 1
Preliminaries
Chapter 1 — what the book is for, why Python, and getting set up
Five short sessions to set the scene: what kind of data the book deals with, why Python won, the seven libraries everything else builds on, how to install them today, and the conventions every later chapter assumes.
What Is This Book About?
Concept
- The book is about the nuts and bolts of manipulating, processing, cleaning and crunching data in Python — not about statistics or machine learning theory.
- By "data" it means structured data: tables where each column may be a different type (a spreadsheet, a CSV, a SQL table), multidimensional arrays, multiple tables linked by key columns, and time series.
- Most of the real work in analysis is getting data into that shape — McKinney calls it data wrangling or munging, and it is what the tools in this book are built for.
- Almost any dataset can be turned into a structured form: a folder of news articles becomes a table of word frequencies, a web log becomes a table of timestamped events.
Key Terms
- Structured data
- data in rows and columns (or arrays) with a consistent shape
- Tabular data
- rows of records, each column a named field with its own type
- Data wrangling
- cleaning, reshaping and combining raw data until it can be analysed
- Time series
- observations recorded at points in time, evenly or unevenly spaced
Worked example
import pandas as pd
# one table: each row a record, each column a typed field
scores = pd.DataFrame({
"student": ["Ploy", "Ton", "Mint"],
"grade": [8, 8, 9],
"score": [72.5, 88.0, 91.5],
})
print(scores) student grade score
0 Ploy 8 72.5
1 Ton 8 88.0
2 Mint 9 91.5 Exercise
List three datasets you use outside of programming (a class register, a phone bill, a sports table). For each, name its rows and three of its columns.
Which of the four kinds of structured data is each one: tabular, multidimensional array, multiple linked tables, or time series? Some fit more than one.
Why Python for Data Analysis?
Concept
- Python works as glue: it is easy to wrap fast legacy code written in C, C++ or Fortran, so heavy computation runs in compiled code while you write readable Python on top.
- It solves the two-language problem. Teams used to prototype in R or MATLAB and then rewrite in Java or C++ for production; with Python, research and production can share one language.
- The trade-off: Python is interpreted, so a plain Python loop is much slower than compiled code. That is exactly why NumPy and pandas push the loops down into C.
- It is also a poor fit for highly concurrent, multithreaded work — the GIL (global interpreter lock) stops more than one thread running Python bytecode at a time.
Key Terms
- Glue language
- a language used to connect and drive components written in other languages
- Two-language problem
- prototyping in one language, then rewriting for production in another
- Interpreted
- run line by line by an interpreter rather than compiled to machine code first
- GIL
- global interpreter lock — lets only one thread execute Python code at a time
Exercise
In one sentence each, explain "glue language" and "two-language problem" to someone who has never programmed.
Name one job where Python would be a poor choice and say why (hint: think about speed or many things happening at once).
Essential Python Libraries
Concept
- NumPy is the foundation: the fast multidimensional array (
ndarray) that nearly every other scientific library passes data around in. - pandas adds labelled, table-shaped data — the
DataFrameandSeries— with fast indexing, alignment, missing-data handling, grouping and reshaping. The name comes from panel data and Python data analysis. - matplotlib draws the plots; IPython and Jupyter give you the interactive shell and notebooks you explore data in.
- SciPy covers scientific computing (integration, optimisation, statistics, sparse matrices); scikit-learn is the general-purpose machine-learning toolkit; statsmodels handles classical statistics and econometrics.
- None of these are rivals — a normal analysis uses several at once: load with pandas, compute with NumPy, plot with matplotlib, model with statsmodels or scikit-learn.
Key Terms
- ndarray
- NumPy's fast, fixed-type, n-dimensional array
- DataFrame
- pandas' two-dimensional labelled table
- Jupyter notebook
- a document of runnable code cells, output and notes
- Import convention
- the agreed short names: np, pd, plt, sns, sm
Exercise
For each task, name the library you would reach for first: reading a CSV, multiplying two big matrices, drawing a bar chart, fitting a linear regression, training a classifier.
Use the explorer below to open every library, then write its import line from memory without looking.
Installation and Setup
Concept
- The book recommends Miniconda — a minimal install of the conda package manager — with the community conda-forge channel, so you get compiled packages without needing a C compiler.
- Work in a separate environment per project, so one project upgrading pandas never breaks another.
pipwith a virtual environment (python -m venv) works too — modern pandas and NumPy ship prebuilt wheels for Windows, macOS and Linux.- What changed since my first-edition copy: it installed "EPDFree" and ran
easy_install pandas, which needed gcc on Linux. Both are long obsolete — don't follow old install instructions. - Any editor works; the book's habit is IPython or Jupyter plus a text editor. VS Code and PyCharm both run notebooks directly.
Key Terms
- conda
- a package and environment manager that installs compiled libraries
- conda-forge
- the community channel with up-to-date builds of scientific packages
- Environment
- an isolated set of packages for one project
- venv + pip
- Python's built-in alternative: a virtual environment plus the standard installer
Worked example
# conda route (the book's) — run in a terminal, not in Python
conda config --add channels conda-forge
conda config --set channel_priority strict
conda create -y -n pydata-book python=3.12
conda activate pydata-book
conda install -y pandas jupyter matplotlib
# pip route
python -m venv .venv
# Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
pip install pandas jupyter matplotlib Exercise
Create an environment called pydata-book and install pandas, jupyter and matplotlib. Start Python and run import pandas as pd; print(pd.__version__).
Start a notebook with jupyter notebook (or open a .ipynb in VS Code) and run one cell that prints the NumPy and pandas versions.
Navigating This Book
Concept
- Code examples are shown the way they look in IPython: an
In [5]:prompt for what you type andOut[5]:for the result. - The example datasets are in the book's GitHub repository, wesm/pydata-book — clone or download it so file paths like
examples/ex1.csvwork. - Every example assumes the same import conventions. Use them yourself — anyone reading your code will expect
npandpd. - The book also sets NumPy to print fewer decimals, so your output may show more digits than the text — that is display only, not a different answer.
Key Terms
- In [n] / Out [n]
- IPython prompts numbering each input and its result
- pydata-book
- the GitHub repository with all example datasets
- np.set_printoptions
- controls how many decimals NumPy prints
Worked example
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels as sm
np.set_printoptions(precision=4, suppress=True)
pd.options.display.max_rows = 20 Exercise
Download the pydata-book repository and load examples/ex1.csv with pd.read_csv. Print the first rows with .head().
Make a "starter cell" with the import conventions and print options above, and paste it at the top of every notebook in this course.