DS 208 · Week 9

Working with Data Sources

File formats other than CSV, rows retrieved from a SQL database, and live data from a web API.

Programming for Data Science · University of the Philippines Cebu

Outline

Three sources of data

Key terms

Ten terms used this week

file format

The agreed layout of the data inside a file; it determines which reader is used.

e.g. CSV, JSON, Excel, Parquet → read_csv, read_json, …

JSON

Text written like Python lists and dictionaries; the usual format of web replies.

e.g. [{"city": "Cebu", "pop": 964000}]

encoding

The codebook that converts a file's bytes into letters. An incorrect one garbles ñ.

e.g. encoding="utf-8"

file path

A file's address: the sequence of folders, then its name.

e.g. data/raw/flood.csv

database / table

A store of many named tables that is queried rather than opened like a file.

e.g. the cities table inside cities.db

SQL query

One question to a database, written in SQL: which columns, from which table, which rows.

e.g. SELECT city FROM cities WHERE pop > 900000

connection

An open link between a program and a database; queries are sent through it.

e.g. conn = sqlite3.connect("cities.db")

API / endpoint

A web address built for programs; each endpoint is one address that serves one kind of data.

e.g. /api/flood/projects

request / response

The message sent to a web server, and the reply it returns.

e.g. r = requests.get(url) — r is the response

status code

The three-digit number on every response indicating whether it succeeded.

e.g. 200 OK, 404 not found, 429 too many requests

Previous session

Data sources covered so far

All analyses so far began with read_csv. Data is also stored in databases and served by web APIs. The result is the same DataFrame; only the access method differs.

Prerequisites

DataFrame
pandas' table: rows and named columns (week 6)
dtype
a column's data type, e.g. int64, float64, object (text)
dictionary
Python's name → value lookup, {"city": "Cebu"} (week 3)
merge
combine two tables by matching a key column (week 7)

What stays the same

Once loaded, the data is a DataFrame, and all pandas methods apply.

What changes

The access method: a file reader, a SQL query, or an HTTP request.

About the tool

SQL dates from the 1970s; SQLite from 2000

1970

Tables

Edgar F. Codd at IBM proposes storing data as related tables.

1974

SEQUEL

Donald Chamberlin and Raymond Boyce at IBM design a language to query them.

1986

A standard

Renamed SQL, it becomes an ANSI standard (ISO in 1987).

2000

SQLite

D. Richard Hipp writes a small database for US Navy ship software.

SourceWikipedia: SQL; Wikipedia: SQLite

About the tool

How widely SQLite is used

Sourcesqlite.org: Most widely deployed; Python docs: sqlite3

Runnable code

Files and SQL run on these slides

As in weeks 5 to 8, a block with a ▶ Run / Edit button runs in the browser. This week that includes writing and reading files, and SQL: the browser’s Python has SQLite built in, and the files live in the page’s own memory.

What does not run here

The browser cannot download from the internet, so the flood data and every API call have no button; the companion notebook runs them. Parquet needs a library the browser lacks.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

File formats

One reader per format.

CSV files are loaded with read_csv. This part covers the other common file formats (the agreed layout of the bytes inside a file) and two frequent sources of error: text encoding and file paths.

Limitations of CSV

CSV is simple but does not store types

A CSV stores only text: types are inferred on load, and nesting is not possible. JSON preserves structure, Excel preserves sheets, and each suits different uses.

Key terms

CSV
"comma-separated values": plain text, one row per line, commas between cells
JSON
text written like Python lists and dictionaries: [{"city": "Cebu", "pop": 964000}]
Excel
a spreadsheet file (.xlsx) that can hold several sheets
nesting
a value that itself holds values, like a dictionary inside a dictionary

CSV

Flat text; widely supported, but types are lost.

JSON

Nested and self-describing; the standard web format.

Excel

Multiple sheets; common in office settings.

JSON

JSON is text resembling Python data

JSON (JavaScript Object Notation) writes data as plain text using two structures from week 3: [ ] for a list and { } for a dictionary of key: value pairs. Almost every web API responds in JSON.

A CSV is a paper grid, whereas JSON is a set of labelled index cards in which every value carries a label and a card can contain smaller cards.

import json import pandas as pd txt = '[{"city": "Cebu", "pop": 964000}, {"city": "Davao", "pop": 1777000}]' data = json.loads(txt) print(type(data), type(data[0])) print(pd.DataFrame(data)) <class 'list'> <class 'dict'> city pop 0 Cebu 964000 1 Davao 1777000
  • txt = '[{…}, {…}]'JSON is text (a string): here, a list holding two records
  • json.loads(txt)"load string": convert the JSON text into Python objects
  • <class 'list'> <class 'dict'>the outside is a list; each item in it is a dictionary
  • pd.DataFrame(data)one row per dictionary, one column per key
The small tables

Week 7’s eight cities, with their areas

The file and SQL examples this week save, read and query the eight cities from week 7 and their land areas. The flood data appears later, for the measurements.

  • citieseight cities: name, island group (region) and approximate 2020 population
  • areasthe land area of each city in km²

SourceLand areas from each city’s Wikipedia article, rounded to whole km²; populations are approximate 2020 census figures.

import io csv_text = """city,region,pop Quezon City,Luzon,2960000 Manila,Luzon,1847000 Baguio,Luzon,366000 Cebu,Visayas,964000 Iloilo,Visayas,457000 Tacloban,Visayas,251000 Davao,Mindanao,1777000 Cagayan de Oro,Mindanao,728000""" cities = pd.read_csv(io.StringIO(csv_text)) areas = pd.DataFrame({ "city": ["Quezon City", "Manila", "Baguio", "Cebu", "Iloilo", "Tacloban", "Davao", "Cagayan de Oro"], "area_km2": [172, 42, 58, 315, 78, 202, 2444, 413]}) print(cities.shape, areas.shape) (8, 3) (8, 2)
Readers

pandas readers for each format

The pattern is identical: read_ plus the format. Excel files can hold many sheets, so the required sheet is named.

The text in quotes is a file path: the file's address on the computer. A bare name such as "data.csv" means "in the same folder as this notebook".

# cities: the eight-city table from week 7 cities.to_csv("cities.csv", index=False) cities.to_json("cities.json", orient="records") print(pd.read_csv("cities.csv").shape) print(pd.read_json("cities.json").shape) (8, 3) (8, 3)
  • cities.to_csv("cities.csv", index=False)write week 7’s eight cities to a CSV file, without the row numbers
  • to_json(…, orient="records")write the same table as JSON: a list with one dictionary per row
  • pd.read_csv / pd.read_jsonread each file back: the same 8 × 3 table; pd.read_excel(path, sheet_name=…) reads one Excel sheet the same way
Comparison

Four file formats compared

FormatBest forReader
CSVsimple, shareable tablesread_csv
JSONnested data, web responsesread_json
Excelmulti-sheet office filesread_excel
Parquetbig data, fast + typedread_parquet
Case study

The flood data, loaded from the course API

The format comparisons use the 34,079 flood projects. The CSV text is kept in text, so later slides can read it again with different options.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" text = requests.get(url, timeout=60).text df = pd.read_csv(io.StringIO(text)) print(df.shape) print(round(len(text) / 1e6, 2), "MB of CSV text") (34079, 15) 11.44 MB of CSV text
  • requests.get(url, timeout=60).textdownload the whole table as one block of CSV text
  • pd.read_csv(io.StringIO(text))read that text as if it were a file
  • 11.44 MB of CSV textthe size of the download, unzipped
Measured on 34,079 rows

One table stored in five formats

FormatSizeWriteReadKeeps dtypes
CSV11.44 MB119 ms56 msNo — everything is text
CSV.gz2.84 MB338 ms64 msNo
JSON18.31 MB56 ms86 msPartly
Parquet3.34 MB19 ms3 msYes
SQLite11.77 MB80 ms74 msYes
Types in CSV

CSV files have no field for column types

A CSV contains only characters and commas. The week 6 material on pd.to_numeric is needed because the format cannot record that a column is a float.

Parquet stores the schema

The schema is the list of columns and their types. It is stored with the data, so reading it back requires no conversion step and involves no guessing.

# CSV round-trip: types are guessed again on reading df.to_csv("f.csv", index=False) print(pd.read_csv("f.csv").budget.dtype) # Parquet round-trip: types are stored in the file df.to_parquet("f.parquet") print(pd.read_parquet("f.parquet").budget.dtype) float64 float64
  • df.to_csv("f.csv", index=False)write the table to a CSV file; every reader must guess the types again
  • .budget.dtyperead it back and check the type of the budget column
  • float64 / float64the same answer both times, but CSV’s was a guess and Parquet’s was stored in the file
Choosing a format

Three questions for choosing a format

No format is best in general; the choice depends on use. These three questions determine it in most cases.

The choice between a printed letter, a PDF and a shared spreadsheet depends on who will open it and how it will be used.

Note: this course’s dataset

The flood dataset is distributed as gzipped CSV, not Parquet, because the production server lacks pyarrow (the extra library pandas needs to read and write Parquet). Deployment constraints take precedence over benchmarks.

# Will a human open it in Excel? -> CSV # Is it big, and only code reads it? -> Parquet # Does it need querying without loading # the whole thing into memory? -> SQLite # Is it nested (lists inside records)? -> JSON
Exercise · 3 min

pathlib for portable file paths

A hardcoded "C:\\Users\\me\\data.csv" is the most common reason a notebook fails on another computer.

A file path is a file's address: folders separated by / (Mac, Linux) or \ (Windows). A relative path (data/raw/flood.csv) starts from the current folder; an absolute one (C:\Users\…) starts from the top of one particular computer.

Relative to the file, not the cwd

The cwd (current working directory) is the folder in which a program is running. Notebooks may be started from any folder, so paths are anchored to a known point in the project.

Tasks

  1. Predict what print(path) shows.
  2. Select ▶ Run / Edit and run the code.
  3. Change "cities.csv" to "cities.json" and to_csv(path, index=False) to to_json(path, orient="records"). Is the file bigger or smaller?

Result on the lecture laptop (select to reveal)

data/cities.csv True, then 203 bytes. On Windows the same code prints data\cities.csv: pathlib uses each system’s separator. As JSON the file is 412 bytes, twice the size, because every record repeats the column names.

# cities: the eight-city table from week 7 from pathlib import Path path = Path("data") / "cities.csv" path.parent.mkdir(exist_ok=True) cities.to_csv(path, index=False) print(path, path.exists()) print(path.stat().st_size, "bytes")
  • Path("data") / "cities.csv"build the path piece by piece; / joins the pieces with the right separator
  • path.parent.mkdir(exist_ok=True)make the data folder, if it is not there yet
  • path.stat().st_sizethe file’s size in bytes
Cañete

Encoding errors that raise no exception

Some encoding errors raise an exception; others alter the data silently.

A file stores bytes (numbers), not letters. An encoding is the codebook that turns bytes into letters; utf-8 and latin-1 are two common codebooks. Reading with the wrong one turns ñ into ñ.

Exercise · 3 min

Only one failure mode raises an error

This is especially relevant here: Filipino personal and place names often contain ñ, a character on which the two common encodings disagree.

The silent failure is more dangerous

A crash prompts investigation. Mojibake can pass typical tests and reach a published table unnoticed.

Tasks

  1. Predict which of the two attempts raises an error.
  2. Select ▶ Run / Edit and run the code.
  3. Replace "Cañete" with "Peñaranda" in both places. What changes?

Result on the lecture laptop (select to reveal)

Only the first: the latin-1 byte for ñ (0xf1) is not valid utf-8, so decoding raises UnicodeDecodeError. The second prints Cañete with no error at all. With Peñaranda: the same error, at position 2, and Peñaranda.

raw = "Cañete".encode("latin-1") # bytes written by an old system try: raw.decode("utf-8") # read as utf-8 -> CRASH except UnicodeDecodeError as e: print("UnicodeDecodeError:", e) # utf-8 bytes read as latin-1 -> SILENT print("Cañete".encode("utf-8").decode("latin-1"))
  • Reading the errorthe last line is read first: UnicodeDecodeError is the error type — the bytes are not valid in the named codebook
  • byte 0xf1 in position 2the problem is byte 0xf1 (ñ in latin-1), third character in (counting from 0): "Cañete"
  • .encode("utf-8").decode("latin-1")turn the text into utf-8 bytes, then read them with the wrong codebook
  • 'Cañete'mojibake: garbled letters from the wrong encoding, with no error at all
Worked example

Specifying the encoding explicitly

The encoding is stated when reading. If it is unknown, the bytes are inspected rather than trying encodings until one raises no error.

utf-8-sig for files from Excel

Excel writes a byte-order mark. Plain utf-8 leaves it in the first column name as an invisible character, so lookups by that name fail.

with open("towns.csv", "w", encoding="utf-8-sig") as f: # as Excel saves it f.write("town\nCañete\nPeñaranda\n") with open("towns.csv", "rb") as f: print(f.read(4)) # the first bytes reveal the encoding print(pd.read_csv("towns.csv", encoding="utf-8-sig").town.tolist()) print(pd.read_csv("towns.csv", encoding="latin-1").iloc[:, 0].tolist()) b'\xef\xbb\xbft' ['Cañete', 'Peñaranda'] ['Cañete', 'Peñaranda']
  • encoding="utf-8-sig"utf-8 that also skips the invisible marker Excel puts at the start (a BOM)
  • open("towns.csv", "rb")open the file in “read bytes” mode, without decoding
  • b'\xef\xbb\xbft'the first bytes: \xef\xbb\xbf is the BOM, so the file is utf-8 from Excel
Selecting columns

usecols: about 14× less memory

Most analyses use three or four columns. Loading fifteen and ignoring eleven wastes memory and time.

Measured on this dataset

Two columns: 25 ms and 1.0 MB. All fifteen: 59 ms and 13.6 MB (memory measured with memory_usage(deep=True)). The saving increases with file size.

import time def load(**kw): t = time.perf_counter() d = pd.read_csv(io.StringIO(text), **kw) ms = (time.perf_counter() - t) * 1000 mb = d.memory_usage(deep=True).sum() / 1e6 print(f"{ms:4.0f} ms, {mb:4.1f} MB, {d.shape[1]} columns") load() load(usecols=["region", "budget"]) 59 ms, 13.6 MB, 15 columns 24 ms, 1.0 MB, 2 columns
  • usecols=["region", "budget"]load only these two columns and skip the other thirteen
  • memory_usage(deep=True).sum()bytes the table really takes, text included
  • dtype=…, parse_dates=…also worth setting on read: column types and date columns, decided once
Files larger than memory

chunksize returns an iterator

Beyond a certain size, the table cannot be held in memory. It is processed in pieces, and only the summary is kept.

A chunk is one piece of the file, here 5,000 rows. An iterator supplies the pieces one at a time, in a loop.

7 chunks, about 2.0 MB at a time

Against 13.6 MB for the whole frame. At 34k rows this is a demonstration; at 34M rows it is necessary.

total, n, chunks, peak = 0, 0, 0, 0 for chunk in pd.read_csv(io.StringIO(text), chunksize=5000): total += chunk.budget.sum() n += len(chunk) chunks += 1 peak = max(peak, chunk.memory_usage(deep=True).sum()) print(chunks, n, round(total / 1e12, 3)) # trillions of pesos print(round(peak / 1e6, 1), "MB in memory at most") 7 34079 1.6 2.0 MB in memory at most
  • pd.read_csv(…, chunksize=5000)read 5,000 rows at a time instead of the whole file
  • total += chunk.budget.sum()keep a running total; each chunk is then dropped
  • 7 34079 1.67 chunks, all 34,079 rows, ₱1.6 trillion in all
Exercise · 3 min

json_normalize flattens nested records

APIs return records with objects inside them. pd.DataFrame leaves those as dicts in a cell; json_normalize expands them into columns.

Dotted names show the nesting

loc.region came from {"loc": {"region": ...}}. Columns can be renamed afterwards, but the default name records the origin of each value.

Tasks

  1. Predict the column names of the result.
  2. Select ▶ Run / Edit and run the code.
  3. Add a third record, {"id": 3, "loc": {"region": "NCR"}}, with no province. What does its row show?

Result on the lecture laptop (select to reveal)

id, loc.region and loc.prov: one column per path into the nested dictionaries. The third record has no prov, so its loc.prov is NaN.

nested = [ {"id": 1, "loc": {"region": "III", "prov": "Bulacan"}}, {"id": 2, "loc": {"region": "V", "prov": "Albay"}}, ] print(pd.json_normalize(nested))
  • nested = [ {…}, {…} ]a list of two records; each has a loc dictionary inside it
  • pd.json_normalize(nested)flatten: each inner key becomes its own column
  • loc.regionthe dot in the column name says "region, from inside loc"
Review question

Question (select to reveal the answer)

A cleaned 34,079-row table will be read only by code, and file size and load time matter. Which format is most suitable?

A · CSV — it is universal
B · Parquet — 3.4× smaller than CSV, fastest to write, and it keeps the dtypes
C · JSON — it preserves structure
D · Excel — anyone can open it
B. Measured on this dataset: Parquet 3.34 MB / 19 ms write against CSV 11.44 MB / 119 ms, and it records the schema so no to_numeric step is needed on read. JSON performed worst on size and read time (18.31 MB, slowest read). CSV is appropriate when a person needs to open the file, which was not the requirement here.
Part B

SQL

Query a database; load the result.

Part A covered reading data from files. This part reads data from a database by sending it a question written in SQL; each operation has a pandas equivalent.

Limits of files

Databases scale beyond CSV files

A CSV cannot handle millions of rows, many simultaneous writers or related tables. A database can, and SQL is the language used to query it.

Key terms

database
a program (or file) that stores many tables and answers questions about them
table
one named grid of rows and columns inside a database, like one sheet
SQL
"Structured Query Language", said "sequel" or "S-Q-L": the language for querying databases
query
one question written in SQL, e.g. SELECT city FROM cities

A database is a library in which a request slip (a query) returns only the requested pages, rather than every book (the whole CSV).

Handles size

Queries stay fast on data too big to open in memory.

Handles sharing

Many users share one consistent source of data.

Exercise · 3 min

Query structure: SELECT, FROM, WHERE

A query names the columns, the table and a condition. It uses the same filter-and-select logic as pandas.

SQL keywords are written in capitals by convention (SQL ignores their case); text values go in single quotes; the ; marks the end of the query.

Tasks

  1. Predict the rows the query returns, and their order.
  2. Select ▶ Run / Edit and run the code.
  3. Change 'Visayas' to 'Luzon' and DESC to ASC. Which cities, in which order?

Result on the lecture laptop (select to reveal)

Cebu (964,000), Iloilo (457,000) and Tacloban (251,000): the Visayan cities, largest first. With Luzon and ASC: Baguio, Manila, Quezon City, smallest first.

# cities: the eight-city table from week 7 import sqlite3 con = sqlite3.connect(":memory:") # a database in memory cities.to_sql("cities", con, index=False) query = """ SELECT city, pop FROM cities WHERE region = 'Visayas' ORDER BY pop DESC; """ print(pd.read_sql(query, con))
  • sqlite3.connect(":memory:")a database held in memory, gone when the program ends
  • cities.to_sql("cities", con, index=False)copy the DataFrame into a database table called cities
  • SELECT … FROM … WHERE … ORDER BY …the columns, the table, the rows to keep, and their order (DESC = largest first)
SQL to pandas

read_sql returns a DataFrame

The query is passed as a string through a database connection, and the result is returned as a DataFrame for use with the pandas methods of the last three weeks.

A connection is an open link between a program and the database: it is opened once, queries are sent through it, and it is closed at the end.

# con: the database from the previous slide result = pd.read_sql("SELECT * FROM cities", con) print(type(result)) print(result.shape) <class 'pandas.DataFrame'> (8, 3)
  • pd.read_sql("SELECT * FROM cities", con)send the query through the connection; the answer comes back as a DataFrame
  • <class 'pandas.DataFrame'>so everything from weeks 6 to 8 works on it
SQL and pandas

SQL operations and their pandas equivalents

TaskSQLpandas
Pick columnsSELECT a, bdf[["a","b"]]
Filter rowsWHERE x > 5df[df.x > 5]
SortORDER BY xsort_values("x")
Summarise per groupGROUP BY rgroupby("r")
SQL on the flood data

A groupby written in SQL

This query performs the same operation as the week 7 pandas groupby. Recognising such equivalences is a large part of learning SQL.

  • COUNT(*) AS ncount the rows in each group and call the column n; ROUND(SUM(budget) / 1e9, 1) totals the budgets in billions
  • GROUP BY regionone group per region, exactly like groupby("region")
  • ORDER BY total_b DESC LIMIT 3largest total first, keep only the top 3

Processing in the database

For a 34,079-row table the difference is small. At 34 million rows, it determines whether the query completes or fails with an out-of-memory error.

import sqlite3 con = sqlite3.connect(":memory:") df.to_sql("projects", con, index=False) query = """ SELECT region, COUNT(*) AS n, ROUND(SUM(budget) / 1e9, 1) AS total_b FROM projects GROUP BY region ORDER BY total_b DESC LIMIT 3 """ print(pd.read_sql(query, con)) region n total_b 0 Region III 5412 267.7 1 National Capital Region 3925 159.2 2 Region V 2814 155.6
SQL and pandas

The same groupby in pandas

The pandas version of the previous query gives the same three regions with the same counts and totals. nlargest(3, "total") does the work of ORDER BY total_b DESC LIMIT 3.

  • .agg(n=("contract_id", "count"), total=("budget", "sum"))COUNT(*) AS n and SUM(budget) AS total
  • .nlargest(3, "total")ORDER BY total_b DESC LIMIT 3
top = (df.groupby("region") .agg(n=("contract_id", "count"), total=("budget", "sum")) .nlargest(3, "total")) top["total_b"] = (top.total / 1e9).round(1) # billions print(top[["n", "total_b"]]) n total_b region Region III 5412 267.7 National Capital Region 3925 159.2 Region V 2814 155.6
Query parameters

Parameterised queries with read_sql

One function connects SQL and pandas. Querying is done in SQL and analysis in pandas, with no loop over a cursor (the low-level object that hands back database rows one at a time).

Guideline: parameterise queries

A query is never built by string concatenation (joining pieces of text). Passing parameters is safer and faster, because the database can reuse its plan (its worked-out way of running that query).

A parameter here is a ? placeholder in the query whose value is passed separately; the database always treats it as data, never as SQL. SQL injection is an attack in which user-supplied text inserts additional SQL into a query.

# con: the database from the previous slide r3 = pd.read_sql( "SELECT * FROM projects WHERE region = ?", con, params=["Region III"]) print(len(r3)) # NEVER: f"... WHERE region = '{user_input}'" # that is an SQL injection, and a quote-mark bug 5412
  • WHERE region = ?a placeholder for a value
  • params=["Region III"]the value for the ?, sent separately and safely
  • f"…'{user_input}'"inserting text directly into the query: a name such as O'Brien breaks it, and malicious text can alter it
Writing a table

Saving results with to_sql

A cleaned table is worth storing. SQLite is a single file that requires no server, which makes it the simplest durable option.

The if_exists argument

replace drops and rebuilds; append adds. An incorrect choice duplicates every row or deletes the table.

written = df.to_sql("projects_copy", con, index=False, if_exists="replace") print(written) print(pd.read_sql("SELECT COUNT(*) AS n FROM projects_copy", con)) 34079 n 0 34079
  • df.to_sql("projects_copy", con, …)save the DataFrame as a database table; it returns the number of rows written
  • if_exists="replace"overwrite the table if it is already there
  • SELECT COUNT(*) …count the rows in the new table: all 34,079 arrived
SQL joins

JOIN: the SQL equivalent of merge

A JOIN is the SQL term for merge (week 7). The join types correspond one to one, as do the common errors: a duplicated key multiplies rows here as well.

LEFT JOIN as the default

The reasoning matches how="left": the main table stays intact and unmatched keys appear as NULL.

# cities, areas: the eight cities and their land areas (week 7) con = sqlite3.connect(":memory:") cities.to_sql("cities", con, index=False) areas.to_sql("areas", con, index=False) query = """ SELECT c.city, c.pop, a.area_km2 FROM cities c LEFT JOIN areas a ON c.city = a.city """ print(pd.read_sql(query, con).head(3)) city pop area_km2 0 Quezon City 2960000 172 1 Manila 1847000 42 2 Baguio 366000 58
  • FROM cities cc is a short alias for the table, used as c.city
  • LEFT JOIN areas a ON c.city = a.citykeep every city, and attach its area where the names match
  • cities.merge(areas, on="city", how="left")the same join in pandas: LEFT JOIN is how="left"
SQL and pandas

The same join in pandas

merge with how="left" returns the same rows as the LEFT JOIN. Each SQL join type has a how= value.

  • how="left"LEFT JOIN: every row of the left table
  • how="inner" / how="outer"INNER JOIN / FULL OUTER JOIN
# cities, areas: the same two tables both = cities.merge(areas, on="city", how="left") print(both.head(3)) # INNER <-> how="inner" LEFT <-> how="left" # FULL <-> how="outer" city region pop area_km2 0 Quezon City Luzon 2960000 172 1 Manila Luzon 1847000 42 2 Baguio Luzon 366000 58
Review question

Question (select to reveal the answer)

What does pd.read_sql(query, conn) return?

A · a raw SQL string
B · a DataFrame
C · a database connection
D · a list of tuples

B — a DataFrame.

read_sql runs the query on the connection and loads the rows directly into a DataFrame, to which pandas methods then apply.

Break

  Five minutes

Next: retrieving live data from the web.

Part C

APIs

Retrieving current data over the web.

Files and databases are usually stored on a local machine or an organisation's network. This part retrieves data from a remote server over the internet, through an API, and converts the JSON reply into a DataFrame.

Conceptual model

An API: a URL that responds with JSON

the program requests.get(url) API server holds the data GET request → ← JSON response then: pd.DataFrame(response.json())
Sending a request

requests.get and the status check

The request is sent, the status is checked (200 means OK), and the body is parsed with .json(). The status is checked before the data is used.

A status code is the three-digit number at the top of every response. 2xx indicates success, 4xx an error in the request (404 = not found, 429 = too many requests), 5xx a server failure.

A courier's tracking status ("delivered", "address not found", "try again later"), read before the parcel is opened.

import requests r = requests.get("https://portal.latarak.com/api/flood", timeout=30) print(r.status_code) # 200 = OK info = r.json() # JSON text -> a Python dict print(type(info)) print(info["rows"], "rows;", info["rate_limit"]) 200 <class 'dict'> 34079 rows; 20/min anonymous, 200/min with the key
  • requests.get(url, timeout=30)send a GET request and wait at most 30 seconds for the reply
  • r.status_codethe number the server replied with; 200 = OK
  • r.json()read the body as JSON: a JSON object becomes a Python dict
Status codes

Six common status codes

CodeNameMeaningWhat to check first
200OKsuccess; the body holds the dataproceed: r.json()
400Bad Requestthe server could not interpret the requestthe parameters in the address
401 / 403Unauthorized / Forbiddenaccess is deniedthe API key: missing, mistyped, expired
404Not Foundnothing lives at that addressthe spelling of the endpoint
429Too Many Requeststhe rate limit was exceededwait (Retry-After), then cache
500Internal Server Errora failure on the server sidetry again later
JSON to DataFrame

Converting a JSON response to a DataFrame

A list of records converts directly into a DataFrame. Standard pandas operations (filter, group, plot) then apply exactly as for a loaded CSV.

import requests url = "https://portal.latarak.com/api/flood/projects" page = requests.get(url, params={"limit": 3}, timeout=30).json() print(list(page)) # the keys of the reply first = pd.DataFrame(page["results"]) print(first[["contract_id", "region", "status"]]) ['next', 'page', 'pages', 'per_page', 'prev', 'results', 'total'] contract_id region status 0 22F00136 Region V Completed 1 18BI0029 Region II Completed 2 19CD0029 Region III Completed
  • params={"limit": 3}requests adds ?limit=3 to the address for you
  • list(page)the keys of the reply: the records sit under results
  • pd.DataFrame(page["results"])a list of dictionaries becomes a table, one row each
Course API

The course API for practice

This portal serves the flood dataset at the endpoint /api/flood. It is the same data previously loaded from disk, accessed as a real service would provide it.

A self-describing API

A request to the root returns its endpoints, its licence, and its data-quality warnings, as a well-designed API should.

Try it without code first

The API Playground on this portal sends these requests on click and shows the JSON, then gives the Python to copy into a notebook.

import requests r = requests.get("https://portal.latarak.com/api/flood", timeout=30) print(r.status_code) print(r.json()["rows"]) print(r.json()["data_quality_warning"]["field"]) 200 34079 amount_paid
  • r.status_code → 200the request worked
  • r.json()["rows"]the reply is a dictionary; look up its "rows" key: 34,079 projects available
  • ["data_quality_warning"]another key: the API warns that one column is unreliable
Paging

Large collections are returned one page at a time

APIs do not usually return 34,079 records in one response. Each response contains a window of records and a link to the next. This is called paging (or pagination), as with the pages of search results.

Following next until it is null

Page numbers are not computed locally. The server knows how many pages exist; local arithmetic can drift.

import requests BASE = "https://portal.latarak.com" HEAD = {"X-API-Key": "latarak-demo"} url = BASE + "/api/flood/projects?limit=100" rows, pages = [], 0 while url and pages < 3: # all 34,079 rows = 341 pages r = requests.get(url, headers=HEAD, timeout=30).json() rows.extend(r["results"]) url = r["next"] # None after the last page pages += 1 print(len(rows), r["pages"]) 300 341
  • ?limit=100a query parameter: 100 records per page
  • while url and pages < 3:loop while there is a next page; stopped after 3 here, since all 34,079 rows would take 341 requests
  • url = r["next"]the server supplies the address of the next page (None after the last)
Rate limits

Rate limits, API keys and server load

A rate limit is the maximum number of requests a server accepts from one client per minute. An API key is a password-like code that identifies the client to the API. The flood API allows 20 requests a minute anonymously and 200 with the demo key. Exceeding the limit returns a 429 with a Retry-After header stating how long to wait.

Caching fetched data

Data is downloaded once, saved to disk, and then read from the file. Re-downloading the same data on every notebook run is the most common reason students are blocked.

import time, requests BASE = "https://portal.latarak.com" HEAD = {"X-API-Key": "latarak-demo"} # the course's demo key r = requests.get(BASE + "/api/flood/regions", headers=HEAD, timeout=30) if r.status_code == 429: # too many requests time.sleep(int(r.headers["Retry-After"])) r = requests.get(BASE + "/api/flood/regions", headers=HEAD, timeout=30) print(r.status_code, len(r.json()["results"]), "regions") 200 18 regions
  • HEAD = {"X-API-Key": "latarak-demo"}a header sent with the request; the key raises the limit from 20 to 200 requests a minute
  • if r.status_code == 429:429 = too many requests: wait as long as Retry-After says, then try again
  • 200 18 regionsthis time the request was within the limit
Network errors

Handling network errors with try/except

A timeout is how long to wait for a reply before giving up. A file read fails immediately or not at all. A network call can hang, time out, return HTML instead of JSON, or succeed with an error body.

Guideline: set a timeout

Without one, requests waits indefinitely. A hung cell is harder to diagnose than a failed one, because it appears to be running.

import requests url = "https://portal.latarak.com/api/flood/projects/NO-SUCH-ID" try: r = requests.get(url, timeout=10) r.raise_for_status() # 4xx/5xx -> raise data = r.json() except requests.Timeout: print("server too slow: using the cache") except requests.HTTPError as e: print("status", e.response.status_code) except ValueError: print("not JSON: got HTML?") status 404
  • try: … except …:week 4: try the risky lines; each except handles one kind of failure
  • r.raise_for_status()turn a 4xx or 5xx status code into an error
  • status 404the made-up contract id does not exist, so the HTTPError branch ran
Responsible API use

APIs run on servers maintained by others

Review question

Question (select to reveal the answer)

An API returns 429 with a Retry-After: 37 header. What should the code do?

A · Retry immediately — the request probably failed
B · Wait 37 seconds, then retry; and cache results so data is not re-fetched
C · Switch to a different API
D · Send the requests in parallel to finish before the limit applies
B. 429 means the rate limit was exceeded, and the server has specified how long to wait. Retrying immediately (A) or parallelising (D) worsens the problem and leads to blocking. Caching to disk is the lasting fix: fetch once, then work from the file.
Review question

Question (select to reveal the answer)

A request returns r.status_code == 200. What does that mean?

A · the server errored
B · the request succeeded
C · the page was not found
D · the client was rate-limited

B — the request succeeded.

200 means OK. 404 is not found, 429 is too many requests, and 500 is a server error. The status is checked before calling .json().

Exercise · 8 min

Loading one dataset from several sources

1 · Benchmark the formats

Load the flood CSV. Save it as CSV, JSON and SQLite. Compare file sizes with os.path.getsize and check whether they reproduce the benchmark table from Part A.

2 · Query it

Write it to SQLite. Get total budget per region in SQL, then the same in pandas. Confirm the numbers match.

3 · Fetch it

Pull 3 pages from /api/flood/projects with the demo key. Build a DataFrame from the results.

4 · Read the warning

Request /api/flood and print data_quality_warning. Describe the incorrect headline that would result from trusting that column.

Summary table

Data sources covered this week

SourceRead withPoints to check
CSVpd.read_csvNo dtypes; encoding; use usecols
Parquetpd.read_parquetNeeds pyarrow installed — not on every server
Excelpd.read_excelsheet_name; BOM → utf-8-sig
SQLpd.read_sqlParameterise — never f-string a query
APIrequests + pd.DataFrameTimeout, 429s, paging, and cache the result
This week's lab

Loading four sources into DataFrames

The lab reads a JSON and an Excel file, queries a small SQLite database, and fetches data from a public API, loading each into a DataFrame for summary. About 45 minutes.

Lab tasks

read_json/read_excel, read_sql, and requests.get().json().

Optional extension

Add a WHERE clause so the database, not pandas, does the filtering.

Summary

Many sources, one DataFrame

Glossary

This week’s terms, one line each

Files and databases

file format
the layout of data inside a file: CSV, JSON, Excel, Parquet
CSV
plain text, commas between cells; stores no types
JSON
text shaped like Python lists and dictionaries
Parquet
compact column-based format that records each column's type
encoding
the codebook from bytes to letters (utf-8, latin-1)
mojibake
garbled letters (ñ) from reading with the wrong encoding
file path
a file's address: folders, then the file name
chunk
one piece of a big file, read and processed at a time
database / table
a store of named tables / one grid of rows and columns in it
SQL query
one question in SQL: SELECT columns FROM table WHERE condition
connection
the open line to a database that queries travel through
parameter (?)
a placeholder filled safely with a value; prevents SQL injection

Web APIs

API / endpoint
a web address for programs / one address serving one kind of data
HTTP
the rules programs use to talk to web servers
request / response
the message sent / the reply returned
status code
the reply's three-digit verdict: 200 OK, 404 not found, 429 too many requests
API key
a password-like code that identifies the client; kept out of code
rate limit
the maximum requests a server accepts from one client per minute
paging
getting a big result one page at a time, following "next"
timeout
how long to wait for a reply before giving up
cache
a saved copy that avoids downloading the same data twice
JOIN
SQL's word for merge: combine tables on a key
Preparation for next week

Practice & reading

Next Week

Text processing & regular expressions

Cleaning, searching, and extracting from irregular text (phone numbers, dates, codes) with Python's string tools and regex.

DS 208 · Programming for Data Science