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
CSV, JSON, Excel — each with a one-line pandas reader.
Query a database and load the result.
Retrieve current data over the web as JSON.
Real projects rarely start with a clean CSV. Locating the data and accessing it is a substantial part of the work.
A file is a book on one’s own shelf, a database is a library that supplies only the requested pages, and an API is a menu from which data is ordered and delivered.
Load data from a database and from a live API into a DataFrame.
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, …
Text written like Python lists and dictionaries; the usual format of web replies.
e.g. [{"city": "Cebu", "pop": 964000}]
The codebook that converts a file's bytes into letters. An incorrect one garbles ñ.
e.g. encoding="utf-8"
A file's address: the sequence of folders, then its name.
e.g. data/raw/flood.csv
A store of many named tables that is queried rather than opened like a file.
e.g. the cities table inside cities.db
One question to a database, written in SQL: which columns, from which table, which rows.
e.g. SELECT city FROM cities WHERE pop > 900000
An open link between a program and a database; queries are sent through it.
e.g. conn = sqlite3.connect("cities.db")
A web address built for programs; each endpoint is one address that serves one kind of data.
e.g. /api/flood/projects
The message sent to a web server, and the reply it returns.
e.g. r = requests.get(url) — r is the response
The three-digit number on every response indicating whether it succeeded.
e.g. 200 OK, 404 not found, 429 too many requests
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.
int64, float64, object (text){"city": "Cebu"} (week 3)Once loaded, the data is a DataFrame, and all pandas methods apply.
The access method: a file reader, a SQL query, or an HTTP request.
Edgar F. Codd at IBM proposes storing data as related tables.
Donald Chamberlin and Raymond Boyce at IBM design a language to query them.
Renamed SQL, it becomes an ANSI standard (ISO in 1987).
D. Richard Hipp writes a small database for US Navy ship software.
SEQUEL lost its vowels because another company already owned the name.
A database engine is the program that stores tables and answers SQL questions about them. SQLite is one that fits in a single file.
SourceWikipedia: SQL; Wikipedia: SQLite
SQLite databases in active use, by its developers’ estimate.
Inside every Android phone and iPhone, and in Chrome, Firefox and Safari.
import sqlite3 works with nothing to install.
Its code is in the public domain: free for any use, with no licence at all.
Sourcesqlite.org: Most widely deployed; Python docs: sqlite3
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.
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.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserOne 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.
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.
[{"city": "Cebu", "pop": 964000}].xlsx) that can hold several sheetsFlat text; widely supported, but types are lost.
Nested and self-describing; the standard web format.
Multiple sheets; common in office settings.
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.
txt = '[{…}, {…}]'JSON is text (a string): here, a list holding two recordsjson.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 dictionarypd.DataFrame(data)one row per dictionary, one column per keyThe 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 populationareasthe 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.
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.to_csv("cities.csv", index=False)write week 7’s eight cities to a CSV file, without the row numbersto_json(…, orient="records")write the same table as JSON: a list with one dictionary per rowpd.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| Format | Best for | Reader |
|---|---|---|
| CSV | simple, shareable tables | read_csv |
| JSON | nested data, web responses | read_json |
| Excel | multi-sheet office files | read_excel |
| Parquet | big data, fast + typed | read_parquet |
For large or frequently reused data, parquet (a compact file format made for data tools) keeps types and loads much faster than CSV.
Every reader has a writer: df.to_csv, to_json, and so on.
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.
pd.read_csv(url)?pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.
requests.get(url, timeout=60).textdownload the whole table as one block of CSV textpd.read_csv(io.StringIO(text))read that text as if it were a file11.44 MB of CSV textthe size of the download, unzipped| Format | Size | Write | Read | Keeps dtypes |
|---|---|---|---|---|
| CSV | 11.44 MB | 119 ms | 56 ms | No — everything is text |
| CSV.gz | 2.84 MB | 338 ms | 64 ms | No |
| JSON | 18.31 MB | 56 ms | 86 ms | Partly |
| Parquet | 3.34 MB | 19 ms | 3 ms | Yes |
| SQLite | 11.77 MB | 80 ms | 74 ms | Yes |
Parquet is a file format built for data tools: stored in columns, compressed, and with each column's type written inside. SQLite is a complete database kept in one file. .gz means the file is zipped (compressed).
Parquet is 3.4× smaller than CSV and the fastest to write, and it records that budget is a float. JSON is the largest and the slowest to read, although it is a common default for saving data. (Best of five runs on the lecture laptop, pandas 3.0.5; times differ by machine.)
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.
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.
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 columnfloat64 / float64the same answer both times, but CSV’s was a guess and Parquet’s was stored in the fileNo 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.
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.
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.
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.
print(path) shows."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.
Path("data") / "cities.csv"build the path piece by piece; / joins the pieces with the right separatorpath.parent.mkdir(exist_ok=True)make the data folder, if it is not there yetpath.stat().st_sizethe file’s size in bytesSome 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 ñ.
This is especially relevant here: Filipino personal and place names often contain ñ, a character on which the two common encodings disagree.
A crash prompts investigation. Mojibake can pass typical tests and reach a published table unnoticed.
"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.
UnicodeDecodeError is the error type — the bytes are not valid in the named codebookbyte 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 allThe encoding is stated when reading. If it is unknown, the bytes are inspected rather than trying encodings until one raises no error.
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.
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 decodingb'\xef\xbb\xbft'the first bytes: \xef\xbb\xbf is the BOM, so the file is utf-8 from ExcelMost analyses use three or four columns. Loading fifteen and ignoring eleven wastes memory and time.
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.
usecols=["region", "budget"]load only these two columns and skip the other thirteenmemory_usage(deep=True).sum()bytes the table really takes, text includeddtype=…, parse_dates=…also worth setting on read: column types and date columns, decided onceBeyond 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.
Against 13.6 MB for the whole frame. At 34k rows this is a demonstration; at 34M rows it is necessary.
pd.read_csv(…, chunksize=5000)read 5,000 rows at a time instead of the whole filetotal += chunk.budget.sum()keep a running total; each chunk is then dropped7 34079 1.67 chunks, all 34,079 rows, ₱1.6 trillion in allAPIs return records with objects inside them. pd.DataFrame leaves those as dicts in a cell; json_normalize expands them into columns.
loc.region came from {"loc": {"region": ...}}. Columns can be renamed afterwards, but the default name records the origin of each value.
{"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 = [ {…}, {…} ]a list of two records; each has a loc dictionary inside itpd.json_normalize(nested)flatten: each inner key becomes its own columnloc.regionthe dot in the column name says "region, from inside loc"A cleaned 34,079-row table will be read only by code, and file size and load time matter. Which format is most suitable?
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.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.
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.
SELECT city FROM citiesA database is a library in which a request slip (a query) returns only the requested pages, rather than every book (the whole CSV).
Queries stay fast on data too big to open in memory.
Many users share one consistent source of data.
SELECT, FROM, WHEREA 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.
'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.
sqlite3.connect(":memory:")a database held in memory, gone when the program endscities.to_sql("cities", con, index=False)copy the DataFrame into a database table called citiesSELECT … FROM … WHERE … ORDER BY …the columns, the table, the rows to keep, and their order (DESC = largest first)read_sql returns a DataFrameThe 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.
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| Task | SQL | pandas |
|---|---|---|
| Pick columns | SELECT a, b | df[["a","b"]] |
| Filter rows | WHERE x > 5 | df[df.x > 5] |
| Sort | ORDER BY x | sort_values("x") |
| Summarise per group | GROUP BY r | groupby("r") |
Heavy filtering belongs in the SQL query, so that less data is transferred; final shaping is done in pandas.
Requesting three specific books from the librarian rather than borrowing the whole shelf and sorting it at home.
The database performs the large reductions; pandas performs the final refinements.
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 billionsGROUP BY regionone group per region, exactly like groupby("region")ORDER BY total_b DESC LIMIT 3largest total first, keep only the top 3For 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.
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 3One 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).
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.
WHERE region = ?a placeholder for a valueparams=["Region III"]the value for the ?, sent separately and safelyf"…'{user_input}'"inserting text directly into the query: a name such as O'Brien breaks it, and malicious text can alter itA cleaned table is worth storing. SQLite is a single file that requires no server, which makes it the simplest durable option.
replace drops and rebuilds; append adds. An incorrect choice duplicates every row or deletes the table.
df.to_sql("projects_copy", con, …)save the DataFrame as a database table; it returns the number of rows writtenif_exists="replace"overwrite the table if it is already thereSELECT COUNT(*) …count the rows in the new table: all 34,079 arrivedA 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.
The reasoning matches how="left": the main table stays intact and unmatched keys appear as NULL.
FROM cities cc is a short alias for the table, used as c.cityLEFT JOIN areas a ON c.city = a.citykeep every city, and attach its area where the names matchcities.merge(areas, on="city", how="left")the same join in pandas: LEFT JOIN is how="left"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 tablehow="inner" / how="outer"INNER JOIN / FULL OUTER JOINWhat does pd.read_sql(query, conn)
return?
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.
SQL retrieves the rows; pandas performs the analysis.
read_sql → DataFrame.
Next: retrieving live data from the web.
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.
An API ("application programming interface") is a web address built for programs, not people. A program sends a request, and the API returns structured data.
/api/flood/projectsThe reply is almost always JSON, which converts directly into a DataFrame.
An API is a restaurant counter, where the menu lists the endpoints, an order is the request, the returned tray is the response, and the kitchen stays hidden.
requests.get and the status checkThe 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.
requests.get(url, timeout=30)send a GET request and wait at most 30 seconds for the replyr.status_codethe number the server replied with; 200 = OKr.json()read the body as JSON: a JSON object becomes a Python dict| Code | Name | Meaning | What to check first |
|---|---|---|---|
200 | OK | success; the body holds the data | proceed: r.json() |
400 | Bad Request | the server could not interpret the request | the parameters in the address |
401 / 403 | Unauthorized / Forbidden | access is denied | the API key: missing, mistyped, expired |
404 | Not Found | nothing lives at that address | the spelling of the endpoint |
429 | Too Many Requests | the rate limit was exceeded | wait (Retry-After), then cache |
500 | Internal Server Error | a failure on the server side | try again later |
The first digit indicates the source: 2 = success, 4 = a problem with the request, 5 = a problem on the server.
Replies at a shop counter: "here it is" (200), "not in stock" (404), "one at a time, please" (429), "the system is down" (500).
A list of records converts directly into a DataFrame. Standard pandas operations (filter, group, plot) then apply exactly as for a loaded CSV.
params={"limit": 3}requests adds ?limit=3 to the address for youlist(page)the keys of the reply: the records sit under resultspd.DataFrame(page["results"])a list of dictionaries becomes a table, one row eachThis 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 request to the root returns its endpoints, its licence, and its data-quality warnings, as a well-designed API should.
The API Playground on this portal sends these requests on click and shows the JSON, then gives the Python to copy into a notebook.
r.status_code → 200the request workedr.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 unreliableAPIs 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.
Page numbers are not computed locally. The server knows how many pages exist; local arithmetic can drift.
?limit=100a query parameter: 100 records per pagewhile url and pages < 3:loop while there is a next page; stopped after 3 here, since all 34,079 rows would take 341 requestsurl = r["next"]the server supplies the address of the next page (None after the last)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.
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.
HEAD = {"X-API-Key": "latarak-demo"}a header sent with the request; the key raises the limit from 20 to 200 requests a minuteif r.status_code == 429:429 = too many requests: wait as long as Retry-After says, then try again200 18 regionsthis time the request was within the limitA 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.
Without one, requests waits indefinitely. A hung cell is harder to diagnose than a failed one, because it appears to be running.
try: … except …:week 4: try the risky lines; each except handles one kind of failurer.raise_for_status()turn a 4xx or 5xx status code into an errorstatus 404the made-up contract id does not exist, so the HTTPError branch ranEvery API has rules on what may be requested and how often.
Rapid repeated calls in a loop are avoided; calls are spaced out and results cached.
An API key functions as a password. It is never committed to git (the version-control tool of week 11) or stored in a notebook.
This connects to DS 227 (the companion course): technical choices have consequences, here for infrastructure owned by others and the people who rely on it.
Keys are stored in an environment variable (a named setting kept by the computer, outside the code), not in code.
An API returns 429 with a Retry-After: 37 header. What should the code do?
A request returns
r.status_code == 200. What does that mean?
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().
The status is checked before the data: 200 indicates success; 4xx/5xx indicates an error to investigate.
200 = OK. The status is checked on every request.
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.
Write it to SQLite. Get total budget per region in SQL, then the same in pandas. Confirm the numbers match.
Pull 3 pages from /api/flood/projects with the demo key. Build a DataFrame from the results.
Request /api/flood and print data_quality_warning. Describe the incorrect headline that would result from trusting that column.
Step 4 is the key step (DS 227, the companion course, covers this error in its week 4): the API documents its own least reliable column, as a good source should.
| Source | Read with | Points to check |
|---|---|---|
| CSV | pd.read_csv | No dtypes; encoding; use usecols |
| Parquet | pd.read_parquet | Needs pyarrow installed — not on every server |
| Excel | pd.read_excel | sheet_name; BOM → utf-8-sig |
| SQL | pd.read_sql | Parameterise — never f-string a query |
| API | requests + pd.DataFrame | Timeout, 429s, paging, and cache the result |
All five produce the same object. Once the data is a DataFrame, the methods from weeks 6 to 8 apply unchanged, which is the main reason to standardise on one.
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.
read_json/read_excel, read_sql, and
requests.get().json().
Add a WHERE clause so the database, not pandas, does the filtering.
read_csv/json/excel/parquet — one reader per format.
SELECT ... WHERE, loaded with read_sql.
requests.get, check status, .json() into a DataFrame.
In summary: whatever the source, the data is loaded into a DataFrame, and then all pandas methods apply.
Begin a project from wherever the data is stored.
SELECT columns FROM table WHERE condition?)Complete and submit the Week 9 lab. Practise fetching an API and loading its JSON without notes.
The requests quickstart — requests.readthedocs.io/en/latest/user/quickstart.
All materials are linked on the course page beside this deck.
Cleaning irregular text with 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