Sub topic 5
Controlling the index, dates and dtypes
This chapter assumes you can run pd.read_sql_query against a sqlite3 connection, as covered earlier, and that you know what a DataFrame index and a dtype are. It shows how to make the DataFrame come back with the right index and column types, instead of fixing them afterwards.
What you get by default
SQLite stores dates as plain text and lets any column hold NULL. Pandas cannot know what you intended, so it guesses from the Python values the driver returns. Create a small table with one NULL and look at the result:
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer TEXT,
total REAL,
qty INTEGER,
created_at TEXT
);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, 2, '2024-01-05'),
(2, 'Grace', 80.0, NULL, '2024-01-09'),
(3, 'Ada', 200.0, 5, '2024-02-01');
""")
df = pd.read_sql_query("SELECT * FROM orders", conn)
print(df.dtypes)You get id as int64, total as float64, and customer and created_at as text (object in most pandas versions). The qty column is float64, not an integer type. Two things went wrong:
- The NULL became
NaN, and a plain NumPy integer column cannot holdNaN, so pandas promoted the whole column to float. created_atis still a string, so you cannot use.dtaccessors or date arithmetic on it.
Three parameters that fix this
read_sql_query has three parameters for these problems. They are applied in a fixed order after the rows are fetched.
Here they are applied together:
df = pd.read_sql_query(
"SELECT * FROM orders",
conn,
index_col="id",
parse_dates={"created_at": "%Y-%m-%d"},
dtype={"qty": "Int64", "customer": "category"},
)
print(df.dtypes)
print(df)Now created_at is datetime64[ns] (the resolution can differ in newer pandas), qty is Int64, and customer is category. The id column is the index, so it no longer appears in df.dtypes. The missing quantity shows as <NA>.
index_col
index_col takes a column name or a list of names. A list produces a MultiIndex, for example index_col=["customer", "created_at"]. The column must be in the SELECT list. If it is not, you get a KeyError. Using index_col is equivalent to calling df.set_index(...) afterwards, but it keeps the intent next to the query.
parse_dates
parse_dates converts text columns to datetimes. It accepts three forms:
| Form | Example | Meaning |
|---|---|---|
| List of columns | `["created_at"]` | Let pandas infer the format |
| Dict of column to format | `{"created_at": "%Y-%m-%d"}` | Parse with a strptime format |
| Dict of column to options | `{"created_at": {"format": "%Y-%m-%d"}}` | Pass keyword arguments to `pd.to_datetime` |
Prefer the format form. It is faster, and it fails loudly on a malformed row instead of guessing. A NULL in a date column becomes NaT.
Some drivers return real datetime objects, for example PostgreSQL timestamp columns. Pandas already converts those, so parse_dates is mainly for text dates and for columns that arrive as integers, such as Unix timestamps. For epoch seconds, use {"created_at": {"unit": "s"}}.
dtype
dtype takes a single dtype or a dict of column to dtype, and it is passed to astype. Three uses are common:
"Int64"(capital I) is the nullable integer type. It keepsqtyas integers and represents NULL as<NA>."category"saves memory for text columns with few distinct values."float32"halves memory for numeric columns where you do not need full precision.
Do not list a column in both dtype and parse_dates. dtype runs first, and converting a column to a non-date type before it is parsed as a date will fail or give wrong values.
Handling NULL deliberately
You can handle NULLs in SQL or in pandas. Handling them in SQL guarantees the result before pandas sees it:
df = pd.read_sql_query(
"SELECT id, COALESCE(qty, 0) AS qty FROM orders",
conn,
index_col="id",
)
print(df.dtypes)Because there are no NULLs left, qty stays int64. Use COALESCE only when 0 is a true default. If "unknown" matters, keep the NULL and use Int64 so that missing values stay distinguishable from zero.
Checking the result
After loading, confirm the types before you build on them:
print(df.dtypes)
print(df.index.name, df.index.is_unique)
print(df.isna().sum())An index that is not unique is allowed, so check it yourself when the column should be a key.
Exercise
A query returns a shipped_at column that contains text such as 2024-03-07 and some NULLs. You want it as a datetime column, and you want order_id as the index. Which arguments do you pass to read_sql_query, and what appears in the rows where shipped_at was NULL?
Show answer
Pass index_col="order_id" and parse_dates={"shipped_at": "%Y-%m-%d"}, and make sure order_id is in the SELECT list. The NULL rows contain NaT (not a time) in shipped_at.