Sub topic 6
What happens when records have different keys
This chapter assumes you can call pd.json_normalize on a list of dicts and know that nested keys become dotted column names. Real JSON rarely has the same keys in every record, so you need to know what the DataFrame looks like when it doesn't.
Missing keys become NaN
json_normalize flattens each record separately. It then builds the table from the union of all keys it saw. A record that lacks a key gets NaN in that column. No error is raised.
import pandas as pd
users = [
{"id": 1, "address": {"city": "London", "geo": {"lat": 51.5}}},
{"id": 2, "address": {"city": "New York"}},
{"id": 3},
]
df = pd.json_normalize(users)
print(df.columns.tolist())
# ['id', 'address.city', 'address.geo.lat']
print(df.isna().sum())
# id 0
# address.city 1
# address.geo.lat 2
# dtype: int64Record 2 has an address but no geo. Record 3 has no address at all. Both cases produce NaN in the leaf columns they lack. The flattening happens at the leaf level, so a missing parent object just means all of its leaf columns are empty for that row.
Column order follows first appearance
Columns appear in the order the keys are first seen, scanning records from top to bottom. A key that first shows up in the third record is placed after all keys from the earlier records.
contacts = [
{"id": 1, "name": "Ada", "email": "[email protected]"},
{"id": 2, "name": "Grace", "phone": "555-0100"},
]
print(pd.json_normalize(contacts).columns.tolist())
# ['id', 'name', 'email', 'phone']If you need a stable layout, select the columns you want with df.reindex(columns=[...]). Missing columns are then created and filled with NaN, even if no record has them.
Missing values change dtypes
NaN is a float. An integer column that contains any missing value is stored as float64, and the integers display as 30.0.
people = [
{"name": "Ada", "age": 36},
{"name": "Grace", "age": 45},
{"name": "Alan"},
]
df = pd.json_normalize(people)
print(df["age"].dtype)
# float64
df["age"] = df["age"].astype("Int64")
print(df["age"].tolist())
# [36, 45, <NA>]The nullable Int64 dtype (capital I) keeps whole numbers and stores the gap as <NA>. Use it when the values are identifiers or counts that should stay integers.
Missing key versus explicit null
JSON can say "age": null instead of omitting the key. In the DataFrame this becomes None or NaN, depending on the column's dtype. Both are caught by isna(), fillna() and dropna(), so you rarely need to tell the two cases apart. If the difference matters, for example "not asked" versus "asked, no answer", check the raw JSON before flattening, because the table loses that distinction.
Common errors
- Assuming every column exists. Code such as
df["address.geo.lat"]raisesKeyErrorif no record in this batch had that path. Usedf.reindex(columns=[...])or checkin df.columns. - Filling too early. Calling
fillna(0)on a column can hide the difference between a real zero and missing data. Decide per column what a gap means. - Expecting an error from
record_pathormeta. The leniency shown here applies to plain flattening. Keys named inmetamust exist in every record unless you passerrors="ignore", which a later chapter covers.
| Situation in the JSON | Result in the DataFrame |
|---|---|
| Leaf key absent from some records | `NaN` in that column for those rows |
| Parent object absent | `NaN` in every leaf column under it |
| Key never appears in any record | No column exists |
| Integer key with gaps | Column becomes `float64` unless converted to `Int64` |
Exercise
Given data = [{"id": 1, "score": 10}, {"id": 2}, {"id": 3, "score": 7}], what dtype does pd.json_normalize(data)["score"] have, and how do you get whole numbers back while keeping the gap?
Show answer
The dtype is float64, because record 2 has no score and the gap is stored as NaN. Convert with df["score"].astype("Int64"), which gives [10, <NA>, 7].