IFI 8410 — Session 8: Python for Data Analysis

Python for Data Analysis

A line of pandas always returns a number

The problem

One line, and it always answers

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 is in this table?

What one row stands for, the column types, what is missing.

Is it fit to compute on?

Which values are wrong, disguised, or impossible.

What does a blank mean?

Zero, unknown, or not applicable.

What does the result leave out?

How many rows it used, and which it dropped.

The tools

Two packages

pandas pd

tables

The DataFrame (a table with named columns) and the Series (one column). Reading and writing CSV and JSON; selecting, joining, grouping; dates and text.

NumPy np

arrays 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

The table is the central structure

Core Python: a loop and a dictionary

totals = {}
for row in records:
    name = row["customer"]
    if name not in totals:
        totals[name] = 0
    totals[name] += row["amount"]

pandas: the loop disappears

deliveries = pd.DataFrame(records)

deliveries.groupby("customer")["amount"].sum()
  • Rows are observations, columns are variables.
  • First question of any table, its grain: what does one row stand for? One order, or one line of an order?
  • Every count and every average depends on the answer.

Concept 2

Vectorized thinking

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"])
  • No loop in sight: the work happens in compiled code, hundreds of times faster on a million rows.
  • Speed is the smaller benefit. The code reads like the sentence: amount is boxes times price.
  • .where(cond) keeps values where the condition holds and blanks the rest; .mask(cond) is the reverse.

Concept 3

Split, apply, combine

Every question with the word per in it has the same three steps.

Split
rows into groups
→
Apply
a calculation to each
→
Combine
the results
KindResultExample
aggregateone row per grouptotal sales per customer
transformone value per original roweach delivery's share of its day's total
filterthe original rows of some groupsonly 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_total

Before writing code, ask: how many rows should the answer have? One per group means aggregate. As many as the table means transform.

Concept 4

A missing value is a question

The blank meansTreat it asThe average…
"nothing happened" — no tip was givenzerocounts the row, with 0
"we do not know" — nobody wrote it downmissingleaves the row out
"does not apply" — a price level for a business with no pricesmissing, perhaps a separate groupleaves 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 this

pandas skips missing values in sums and averages. That default is a decision somebody made on your behalf.

Concept 4, continued

How missing values behave

Arithmetic

Anything computed with a missing value is missing.

Comparisons

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.

Groups

groupby drops rows whose key is missing, unless told dropna=False.

Counting

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

Inspect before you conclude

Five lines of looking

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)

Cleaning: explicit rules

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", ""]))
  • Each rule makes a value missing or corrects its type. None deletes a row silently.
  • Count what each rule changed, and report it with the result.

Worked example — notebook 2

Do more expensive restaurants get better ratings?

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:

  • the price level is text inside a nested dictionary, with the word 'None' for some blanks;
  • some text fields are empty strings, which isna() does not report;
  • a few states have four businesses in them, and their averages mean nothing;
  • restaurants with no listed price are rated differently from the rest, so dropping them changes the comparison;
  • restaurants with a handful of reviews have extreme averages; set them aside and the pattern changes.

Worked example — the result

An answer with its conditions attached

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 number, and how many rows it came from.
  • What was left out, and why.
  • Which meaning of a blank was chosen.

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

Key points

  • A line of pandas always returns a number. Whether it means anything is decided before the line is written.
  • Know the grain: what one row stands for.
  • Describe the column, not the row.
  • "Per" means split, apply, combine. Ask how many rows the answer should have.
  • A blank is zero, unknown, or not applicable. Decide, and say so.
  • Inspect first: shape, types, a few rows, blanks, ranges, distinct values.
  • Report what was left out, with counts.

Now: hands-on

Over to the notebooks

Folder 08-Python-Data-Analysis — work them in this order:

1Thinking in Tables

Concepts

The farm's delivery book: tables, vectorized columns, groupby, and tips that are half empty. Four exercises.

2Yelp Businesses

Worked example

One question, seven steps, on 150,000 real records. Run it on ARC.

3Reference

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

◀ Slides