Tabular data¶
Analysis tools want tables: one row per observation, one column per variable.
This notebook reads and writes CSV with plain Python, the csv module, and pandas, then covers separators, data types, compression, Parquet, files too large for memory, and the conversion between JSON and tables.
Sections: Plain Python, The csv module, pandas, Broken CSV, Other separators, Data types, Compression, Parquet, Large files, Tabular to JSON, JSON to tabular.
Packages beyond the standard library: pandas, pyarrow.
Install them with uv add pandas pyarrow (or pip install).
# The sample files live next to this notebook in data/. In Colab they do not
# exist yet, so this cell downloads them from the course repository.
import pathlib
import urllib.request
base_url = "https://raw.githubusercontent.com/YangKCLab/social-media-analysis/main/docs/topics/data-format-management/data/"
pathlib.Path("data").mkdir(exist_ok=True)
for name in ["sample.csv", "sample_broken.csv", "fips.csv", "sample.json"]:
path = pathlib.Path("data") / name
if not path.exists():
urllib.request.urlretrieve(base_url + name, path)
print(sorted(p.name for p in pathlib.Path("data").iterdir()))
Plain Python¶
CSV stands for comma-separated values. The first line usually names the columns; every other line is one record, with a comma between values.
It is plain text, so a text editor, a spreadsheet, and head all open it.
print(open("data/sample.csv").read())
The obvious way to read it is to split each line on commas.
csv_content = []
with open("data/sample.csv") as f:
for line in f:
csv_content.append(line.strip().split(","))
csv_content
Two things are wrong with this. Every value is a string, so '28' is not a number yet.
And a comma inside a value, such as a name written Davis, Carol, splits into two fields.
Real CSV handles that by wrapping the value in double quotes, and split(",") does not know about the quotes.
The csv module¶
The standard library's csv module reads and writes the quoting rules correctly.
csv.writer quotes a value when it needs to.
import csv
with open("data/quoted.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age", "city"])
writer.writerow(["Davis, Carol", 29, "Boston"])
writer.writerow(['Bob "Bobby" Smith', 34, "San Francisco"])
print(open("data/quoted.csv").read())
csv.reader returns one list per row, and csv.DictReader returns one dictionary per row, keyed by the header line.
Both split "Davis, Carol" as one value.
with open("data/quoted.csv", newline="") as f:
for row in csv.reader(f):
print(row)
with open("data/quoted.csv", newline="") as f:
for row in csv.DictReader(f):
print(row["name"], "->", row["city"])
import pandas as pd
csv_df = pd.read_csv("data/sample.csv")
csv_df
csv_df.dtypes
A column is selected by name and behaves like a typed array. age came back as integers, so arithmetic works on it.
csv_df["age"]
print(csv_df["age"].mean())
to_csv writes a table back out. Pass index=False, otherwise pandas writes its row numbers as an extra first column.
csv_df.to_csv("data/sample_copy.csv", index=False)
print(open("data/sample_copy.csv").read())
Broken CSV¶
data/sample_broken.csv has two damaged rows: line 2 has six values instead of five, and line 4 has an unquoted comma inside a name.
pandas does not raise an error. It reads the file, and the result is wrong in a way that is easy to miss.
print(open("data/sample_broken.csv").read())
pd.read_csv("data/sample_broken.csv")
Because the first data row has one value more than the header, pandas decided the first column is the row index, and every column shifted left.
When a CSV comes from someone else, look at the first rows and the dtypes before analyzing anything.
A column of numbers that arrives as str (object in pandas 2) is the usual sign of a shifted or damaged row.
Other separators¶
The separator does not have to be a comma. Tabs (.tsv) and pipes (|) are common when the values themselves contain commas.
pandas assumes a comma unless told otherwise.
csv_df.to_csv("data/sample_pipe.csv", sep="|", index=False)
print(open("data/sample_pipe.csv").read())
pd.read_csv("data/sample_pipe.csv")
Without sep="|", every line is one value in one column. With it, the table is back.
pd.read_csv("data/sample_pipe.csv", sep="|")
csv_df.to_csv("data/sample_tab.tsv", sep="\t", index=False)
pd.read_csv("data/sample_tab.tsv", sep="\t")
Data types¶
CSV has no types. Everything is text, and the reader guesses.
data/fips.csv holds county FIPS codes, which are five-digit identifiers with leading zeros.
pandas sees digits and guesses integers, and the leading zero disappears.
print(open("data/fips.csv").read())
fips_df = pd.read_csv("data/fips.csv")
fips_df
fips_df.dtypes
dtype tells read_csv the type of a column. Identifiers (FIPS codes, ZIP codes, user IDs, post IDs) are strings, even when they look like numbers: they are never added together, and a leading zero or a 19-digit ID does not survive as an integer.
fips_str_df = pd.read_csv("data/fips.csv", dtype={"fips": "str"})
fips_str_df
fips_str_df.dtypes
Compression¶
pandas reads and writes gzip directly. The .gz extension is enough; compression="gzip" makes it explicit.
fips_str_df.to_csv("data/fips.csv.gz", index=False)
pd.read_csv("data/fips.csv.gz", dtype={"fips": "str"})
Parquet¶
CSV has no types and must be parsed from the first byte. Apache Parquet is a binary, column-oriented format: every column carries its type, the file is compressed, and a reader can load two columns out of fifty without touching the rest.
pandas reads and writes it through the pyarrow package.
fips_str_df.to_parquet("data/fips.parquet")
pd.read_parquet("data/fips.parquet")
The string type of fips survived the round trip. Nobody has to remember the dtype argument.
pd.read_parquet("data/fips.parquet").dtypes
File size depends on the data and on the compression codec. On this table of 200,000 rows, csv.gz beats Parquet's default codec (snappy), and Parquet with zstd beats both.
import os
big = pd.DataFrame({
"id": range(200_000),
"platform": ["bluesky", "4chan", "youtube"] * 66_666 + ["bluesky", "4chan"],
"likes": [i % 50 for i in range(200_000)],
})
big.to_csv("data/big.csv", index=False)
big.to_csv("data/big.csv.gz", index=False)
big.to_parquet("data/big.parquet")
big.to_parquet("data/big_zstd.parquet", compression="zstd")
for name in ["big.csv", "big.csv.gz", "big.parquet", "big_zstd.parquet"]:
print(f"{name:18s} {os.path.getsize('data/' + name) / 1e6:5.2f} MB")
The advantage that does not depend on the data: a CSV reader must parse every byte of every row, and a Parquet reader loads only the columns you ask for.
import timeit
t_csv = timeit.timeit(lambda: pd.read_csv("data/big.csv"), number=5) / 5
t_one = timeit.timeit(lambda: pd.read_parquet("data/big.parquet", columns=["likes"]), number=5) / 5
print(f"read_csv, all columns: {t_csv * 1000:6.1f} ms")
print(f"read_parquet, one column: {t_one * 1000:6.1f} ms")
Large files¶
read_csv loads the whole file into memory. When the file is larger than the memory you have, chunksize returns an iterator of DataFrames and you process one piece at a time.
The same pattern applies to a JSONL file read line by line.
total = 0
rows = 0
for chunk in pd.read_csv("data/big.csv", chunksize=50_000):
total += chunk["likes"].sum()
rows += len(chunk)
print(rows, "rows,", total, "likes")
Tabular to JSON¶
A table converts to JSON without loss: one object per row, column names as keys.
print(fips_str_df.to_json(orient="records", indent=2))
to_dict(orient="records") gives the same rows as Python dictionaries, which is what you want for writing JSONL.
import json
with open("data/fips.jsonl", "w") as f:
for row in fips_str_df.to_dict(orient="records"):
f.write(json.dumps(row) + "\n")
print(open("data/fips.jsonl").read())
JSON to tabular¶
The other direction is the hard one.
A JSON object nests: address holds an object, hobbies holds a list. A table cell holds one value.
pd.json_normalize flattens nested objects into dotted column names.
with open("data/sample.json") as f:
sample_obj = json.load(f)
flat = pd.json_normalize(sample_obj)
flat.columns.tolist()
flat[["name", "age", "address.city", "address.coordinates.latitude", "hobbies"]]
The list in hobbies is still a list inside one cell.
There are two ways out. explode makes one row per list item, which is the right shape for a second table (one row per person-hobby pair).
Or keep the list as a JSON string if it is only carried along and never analyzed.
flat[["name", "hobbies"]].explode("hobbies")
The same steps turn API responses into an analysis table.
Three Bluesky-shaped posts, with a nested author and an optional embed:
posts = [
{"uri": "at://did:plc:a/app.bsky.feed.post/1", "author": {"did": "did:plc:a", "handle": "ana.bsky.social"},
"record": {"text": "first post", "createdAt": "2025-08-26T04:36:32Z"}, "likeCount": 3},
{"uri": "at://did:plc:b/app.bsky.feed.post/2", "author": {"did": "did:plc:b", "handle": "bo.bsky.social"},
"record": {"text": "with a picture", "createdAt": "2025-08-26T05:00:00Z"}, "likeCount": 10,
"embed": {"$type": "app.bsky.embed.images#view", "images": [{"alt": "a cat"}]}},
{"uri": "at://did:plc:a/app.bsky.feed.post/3", "author": {"did": "did:plc:a", "handle": "ana.bsky.social"},
"record": {"text": "third post", "createdAt": "2025-08-27T09:15:00Z"}, "likeCount": 0},
]
posts_df = pd.json_normalize(posts)
posts_df.columns.tolist()
posts_df
json_normalize uses the union of every field it saw, so embed.$type exists for every row and is NaN where the post had no embed.
Pick the columns the question needs, rename them, and fix the types. The result is a table you can save as CSV or Parquet and analyze.
table = posts_df[["uri", "author.handle", "record.createdAt", "record.text", "likeCount"]].rename(columns={
"author.handle": "handle",
"record.createdAt": "created_at",
"record.text": "text",
"likeCount": "likes",
})
table["created_at"] = pd.to_datetime(table["created_at"])
table
table.dtypes
Two rules for this conversion:
- Keep the raw JSON. The table is derived from it, and the next question will need a field you did not keep.
- Do not force everything into one table. Posts, authors, and embedded images are three tables joined by IDs. That is where Databases starts.
# Clean up the files this notebook created.
for name in ["quoted.csv", "sample_copy.csv", "sample_pipe.csv", "sample_tab.tsv", "fips.csv.gz",
"fips.parquet", "fips.jsonl", "big.csv", "big.csv.gz", "big.parquet", "big_zstd.parquet"]:
pathlib.Path("data", name).unlink(missing_ok=True)