Sub topic 5
Flattening only to a chosen depth with max_level
This chapter assumes you can call pd.json_normalize on a list of dictionaries and know that nested keys become dotted column names. It builds on the previous chapter, which covered the sep argument.
Why limit the depth
By default, json_normalize follows every nested object down to its leaf values. That is often what you want. Sometimes it creates columns you will never use, or it splits a sub-object that is more useful kept together. A geo object holding latitude and longitude might be passed whole to a mapping function, for example.
The max_level argument sets how many levels of nested objects get flattened. Top-level keys are level 0. Keys inside a top-level object are level 1, and so on.
Setting max_level
The examples use the same users data as before.
import pandas as pd
users = [
{"id": 1, "name": "Ada", "address": {"city": "London", "geo": {"lat": 51.5, "lng": -0.12}}},
{"id": 2, "name": "Grace", "address": {"city": "New York", "geo": {"lat": 40.7, "lng": -74.0}}},
]
df_full = pd.json_normalize(users)
print(df_full.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo.lat', 'address.geo.lng']
df_shallow = pd.json_normalize(users, max_level=1)
print(df_shallow.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo']
print(df_shallow["address.geo"].iloc[0])
# {'lat': 51.5, 'lng': -0.12}With max_level=1, the address object is flattened once, so address.city becomes a column. The geo object sits one level deeper, so it stays as a Python dict in each cell of address.geo.
The next table shows what each setting produces for this data.
| `max_level` | Columns |
|---|---|
| not set | `id`, `name`, `address.city`, `address.geo.lat`, `address.geo.lng` |
| `1` | `id`, `name`, `address.city`, `address.geo` |
| `0` | `id`, `name`, `address` |
The diagram shows where each setting stops.
Setting max_level=0 keeps address as a single dict column. Setting max_level=1 splits address but keeps geo. Leaving it unset splits everything.
Flattening the leftover dicts later
A dict left in a cell is not lost. You can flatten it later, when you decide you need it, by normalizing that column:
geo = pd.json_normalize(df_shallow["address.geo"].tolist())
print(geo.columns.tolist())
# ['lat', 'lng']
df_joined = df_shallow.drop(columns="address.geo").join(geo.add_prefix("geo_"))
print(df_joined.columns.tolist())
# ['id', 'name', 'address.city', 'geo_lat', 'geo_lng']Calling .tolist() turns the column into a list of dicts, which is the input json_normalize expects. The add_prefix call keeps the new names from colliding with existing columns.
Common mistakes
- Expecting max_level to affect lists. It limits how deep nested objects are flattened. Lists stay as lists either way, and expanding them is the job of
record_path, covered later. - Off-by-one counting. Level 0 is the top level of the record.
max_level=1flattens one layer of nesting, not two. - Treating the leftover cells as strings. The unflattened values are real Python dicts. You can index them with
df["address.geo"].str["lat"], but a string accessor on a dict only works for this indexing shortcut. Other.strmethods will not behave as they do on text. - Forgetting the leftover cells when writing out. A column of dicts can break CSV round trips, because the dicts are written as their string form.
Exercise
Using the users data above, which maxlevel value gives you the columns id, name, address.city and address.geo, with geo still holding a dict in each row? What would maxlevel=0 do to the address column?
Show answer
maxlevel=1 gives those columns. With maxlevel=0 the address object is not flattened at all, so the output has a single address column whose cells are dicts like {'city': 'London', 'geo': {...}}.