← Python for Data Analysis

PDA·05 · Chapter 5

Getting Started with pandas

Chapter 5 — Series, DataFrame, and the essentials of working with them

This is where the book becomes about pandas. Six sessions: the two core data structures, reshaping their labels, the selection rules that trip everyone up (loc vs. iloc), how arithmetic lines up by label, and the one-line summaries you'll use on every dataset.

5.1

Series

  • A Series is a one-dimensional array of values plus an index — a label for each value. Without one, pandas numbers them 0, 1, 2…
  • Select by label (obj["a"]) or with a boolean mask (obj[obj > 0]). NumPy-style maths keeps the labels attached to the values.
  • A Series is like an ordered dict: build one from a dict, and pass index= to choose and order the keys. A key with no value becomes NaN, pandas' marker for missing data.
  • isna() and notna() find the missing values.
  • The big idea: arithmetic aligns on labels, not positions. obj3 + obj4 adds Ohio to Ohio and Texas to Texas, whatever order they are in; labels found in only one side give NaN.
Series
a 1-D labelled array
Index
the labels for each position
NaN
"not a number" — pandas' standard marker for missing values
Alignment
matching values by label before doing arithmetic
import pandas as pd

sdata = {"Ohio": 35000, "Texas": 71000, "Oregon": 16000, "Utah": 5000}
states = ["California", "Ohio", "Oregon", "Texas"]
obj3 = pd.Series(sdata)
obj4 = pd.Series(sdata, index=states)   # no value for California
print(obj4)
print(obj3 + obj4)                      # aligned by state name
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
dtype: float64
California         NaN
Ohio           70000.0
Oregon         32000.0
Texas         142000.0
Utah               NaN
dtype: float64
Activity 1

Make a Series of five classmates' heights with their names as the index. Select everyone taller than the mean.

Activity 2

Make a second Series of weights for four of the same people plus one new person, in a different order. Add the two Series together and explain every NaN.