Sub topic 12
Chunked reads from SQL, JSON Lines and Parquet
This chapter assumes you know read_csv with chunksize, can loop over a reader, and can combine partial results across chunks. Here you apply the same pattern to three other sources. The loop and the combining logic stay the same. Only the way you get an iterator of DataFrames changes.
The common pattern
Each source below gives you a stream of DataFrames. You process each one, keep only a small result, and let the chunk be freed before the next one arrives.
SQL: read_sql with chunksize
pd.read_sql accepts a chunksize argument. With it, the function returns an iterator of DataFrames instead of one large DataFrame. The example uses the standard library sqlite3 module, so it runs without extra packages.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE sales (region TEXT, amount REAL)")
rows = [("north", 10.0), ("south", 20.0), ("north", 30.0), ("south", 40.0), ("east", 5.0)]
conn.executemany("INSERT INTO sales VALUES (?, ?)", rows)
conn.commit()
totals = None
for chunk in pd.read_sql("SELECT region, amount FROM sales", conn, chunksize=2):
part = chunk.groupby("region")["amount"].agg(["sum", "count"])
totals = part if totals is None else totals.add(part, fill_value=0)
totals["mean"] = totals["sum"] / totals["count"]
print(totals)
conn.close()Some database drivers fetch the whole result set into client memory before pandas slices it into chunks. In that case chunksize limits the DataFrame size but not the driver's memory. With SQLAlchemy, you can request a server-side cursor with connection.execution_options(stream_results=True). Support depends on the driver.
Whenever possible, let the database do the filtering and aggregation. A WHERE or GROUP BY in the query is cheaper than pulling rows into Python.
JSON Lines: read_json with lines=True
A JSON Lines file has one JSON object per line. Because each line is independent, the file can be read in pieces. Pass lines=True together with chunksize.
import io
import pandas as pd
data = io.StringIO(
'{"user": "a", "score": 3}\n'
'{"user": "b", "score": 5}\n'
'{"user": "a", "score": 7}\n'
)
best = {}
with pd.read_json(data, lines=True, chunksize=2) as reader:
for chunk in reader:
for user, top in chunk.groupby("user")["score"].max().items():
best[user] = max(top, best.get(user, top))
print(best)chunksize works only when lines=True. A regular JSON file with one large array has to be parsed as a whole, so it cannot be chunked this way.
Parquet: batches with pyarrow
pd.read_parquet has no chunksize option. Use pyarrow to read record batches instead. Parquet also stores data by column, so you can read only the columns you need. This gives a large saving before chunking even starts.
import pandas as pd
import pyarrow.parquet as pq
pd.DataFrame({"id": range(10), "value": [x * 1.5 for x in range(10)]}).to_parquet("demo.parquet")
pf = pq.ParquetFile("demo.parquet")
total = 0.0
for batch in pf.iter_batches(batch_size=4, columns=["value"]):
df = batch.to_pandas()
total += df["value"].sum()
print(total)ParquetFile also exposes pf.metadata.num_row_groups. Row groups are the file's internal blocks, and iter_batches reads them one at a time. A file written as a single huge row group can use more memory than you expect.
Summary of the options
| Source | Call | Requirement |
|---|---|---|
| SQL | `pd.read_sql(query, conn, chunksize=n)` | Driver may still buffer all rows unless streaming is enabled |
| JSON Lines | `pd.read_json(path, lines=True, chunksize=n)` | `lines=True` is mandatory |
| Parquet | `pq.ParquetFile(path).iter_batches(batch_size=n)` | Needs `pyarrow`, and the result is converted with `to_pandas()` |
Exercise
You call pd.readsql("SELECT * FROM events", conn, chunksize=50000) on a very large table, and the process still runs out of memory. Give two changes that could fix it.
Show answer
The driver may be loading the entire result set before pandas splits it into chunks, so enable server-side streaming (for example stream_results=True with SQLAlchemy). Also reduce what is fetched: select only the needed columns and filter or aggregate in the SQL query with WHERE or GROUP BY.