IFI 8410 — Session 8: Python for Data Analysis
A line of pandas always returns a number
The problem
restaurants.groupby("price")["stars"].mean()It does not know about blank cells, a price stored as the word "None", a placeholder date of 1900-01-01, or a group with half its records missing. It computes anyway.
What one row stands for, the column types, what is missing.
Which values are wrong, disguised, or impossible.
Zero, unknown, or not applicable.
How many rows it used, and which it dropped.
The tools
pdtables
The DataFrame (a table with named columns) and the Series (one column). Reading and writing CSV and JSON; selecting, joining, grouping; dates and text.
nparrays of numbers
Fast arithmetic on whole arrays, and the engine underneath pandas. np.where and np.select choose values by a condition.
import pandas as pd and import numpy as np — a convention so universal that code without it looks wrong.
Concept 1
totals = {}
for row in records:
name = row["customer"]
if name not in totals:
totals[name] = 0
totals[name] += row["amount"]deliveries = pd.DataFrame(records)
deliveries.groupby("customer")["amount"].sum()Concept 2
Say what happens to a whole column, not what happens to each row.
deliveries["amount"] = deliveries["boxes"] * deliveries["price_per_box"]
deliveries["large"] = deliveries["boxes"] >= 4
deliveries["discounted"] = np.where(deliveries["boxes"] >= 4,
deliveries["amount"] * 0.9,
deliveries["amount"]).where(cond) keeps values where the condition holds and blanks the rest; .mask(cond) is the reverse.Concept 3
Every question with the word per in it has the same three steps.
| Kind | Result | Example |
|---|---|---|
| aggregate | one row per group | total sales per customer |
| transform | one value per original row | each delivery's share of its day's total |
| filter | the original rows of some groups | only customers with at least five orders |
Concept 3 in code
agg shrinks the table, transform keeps its shape# aggregate: one row per customer
summary = deliveries.groupby("customer", as_index=False).agg(
orders=("amount", "size"),
total=("amount", "sum"),
products=("product", "nunique"),
)
# transform: every row gets its group's value
day_total = deliveries.groupby("date")["amount"].transform("sum")
deliveries["share_of_day"] = deliveries["amount"] / day_totalBefore writing code, ask: how many rows should the answer have? One per group means aggregate. As many as the table means transform.
Concept 4
| The blank means | Treat it as | The average… |
|---|---|---|
| "nothing happened" — no tip was given | zero | counts the row, with 0 |
| "we do not know" — nobody wrote it down | missing | leaves the row out |
| "does not apply" — a price level for a business with no prices | missing, perhaps a separate group | leaves the row out |
tips.mean() # 3.00 blanks left out
tips.fillna(0).mean() # 1.50 blanks counted as zero
tips.isna().sum() # 4 of 8: always report thispandas skips missing values in sums and averages. That default is a decision somebody made on your behalf.
Concept 4, continued
Anything computed with a missing value is missing.
A comparison with a missing value is False. Split tips into "above $2" and "$2 or less" and the blank rows are in neither half.
groupby drops rows whose key is missing, unless told dropna=False.
count counts values; size counts rows.
The worst ones are disguised, and isna() cannot see them: an empty string, the word "Unknown" or "None", a zero that means "not measured", a date of 1900-01-01.
Concept 5
table.shape # rows and columns
table.dtypes # number, or text?
table.head() # what is a row?
table.isna().sum() # where are blanks?
table.describe() # anything impossible?
table["state"].value_counts(dropna=False)dates = pd.to_datetime(table["date"],
errors="coerce")
table["cover"] = table["cover"].where(
table["cover"].between(0, 100))
words = table["kind"].str.strip().str.lower()
table["kind"] = table["kind"].mask(
words.isin(["unknown", ""]))Worked example — notebook 2
150,000 Yelp business records. The question seems to need one line: average stars per price level. On the way to an answer worth giving:
'None' for some blanks;isna() does not report;Worked example — the result
Among restaurants with at least so many reviews and a listed price, the average rating rises by so much per price level; so many records had no price and were left out.
The same applies to the monthly sales-by-region report: a grain error counts freight once per order line, and a region with three orders sits next to one with three thousand as if the averages were equally solid.
To take away
Now: hands-on
Folder 08-Python-Data-Analysis — work them in this order:
Concepts
The farm's delivery book: tables, vectorized columns, groupby, and tips that are half empty. Four exercises.
Worked example
One question, seven steps, on 150,000 real records. Run it on ARC.
Look things up
pandas and NumPy operations to keep open while you work.
As you work, ask of every result: how many rows did it use, and which did it leave out?
Homework: Homework 7: Invasive Plants, from Raw File to Report

