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 that you know how nested keys become dotted column names. It also assumes you know how sep changes the separator. If not, review the earlier chapters on basic json_normalize and column naming first.
By default, json_normalize flattens every nested dictionary it finds, however deep. That is usually what you want. Sometimes it isn't, and the max_level parameter limits how many levels of nesting get flattened.
What max_level counts
max_level is the number of nesting levels below the top level that json_normalize should expand. Any dictionary below that depth stays intact as a Python dict in a single cell.
max_level=Noneis the default. It flattens everything.max_level=0flattens nothing. Top-level keys become columns, and any dictionary value stays in its cell.max_level=1expands the dictionaries at the top level into dotted columns. Dictionaries inside those stay as dicts.max_level=2goes one level deeper, and so on.
The easiest way to see this is to run one document at every depth.
import pandas as pd
doc = {
"id": 1,
"profile": {
"name": "Ada",
"address": {
"city": "London",
"geo": {"lat": 51.5, "lng": -0.12},
},
},
}
for level in range(4):
df = pd.json_normalize(doc, max_level=level)
print(level, df.columns.tolist())
# 0 ['id', 'profile']
# 1 ['id', 'profile.name', 'profile.address']
# 2 ['id', 'profile.name', 'profile.address.city', 'profile.address.geo']
# 3 ['id', 'profile.name', 'profile.address.city', 'profile.address.geo.lat', 'profile.address.geo.lng']At level 3 the output matches what you get with no limit, because the document is only three levels deep. Setting max_level higher than the real depth does no harm.
What the leftover dictionary looks like
A dictionary that is not flattened stays in the DataFrame as an ordinary Python object. You can read it like any other cell.
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 = pd.json_normalize(users, max_level=1)
print(df.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo']
print(df["address.geo"].iloc[0])
# {'lat': 51.5, 'lng': -0.12}
print(type(df["address.geo"].iloc[0]).__name__)
# dictThe column has object dtype, so pandas does no numeric work on it. You can't sort by it, and df["address.geo"] can't be used in groupby or drop_duplicates, because dictionaries are not hashable. Convert the column first if you need those operations.
Why you would stop early
There are three common reasons to set max_level.
- Keys that are data, not structure. Some APIs use identifiers as keys, for example
{"scores": {"u101": 3, "u102": 5, "u103": 4}}. Full flattening creates one column per identifier, which can mean thousands of mostly empty columns. Keeping the dictionary in one cell is more honest. - Wide documents you only partly need. If you want
profile.nameandprofile.addressbut not twenty fields insideaddress, stopping at level 1 keeps the table narrow. - Deferring the decision. You can flatten the shallow levels now and expand the leftover dictionary later, once you know which parts you need.
scores = [
{"course": "intro", "scores": {"u101": 3, "u102": 5}},
{"course": "advanced", "scores": {"u103": 4}},
]
print(pd.json_normalize(scores).columns.tolist())
# ['course', 'scores.u101', 'scores.u102', 'scores.u103']
print(pd.json_normalize(scores, max_level=0).columns.tolist())
# ['course', 'scores']With full flattening, the number of columns grows with the number of distinct identifiers across all records. With max_level=0, the number of columns stays fixed no matter how many identifiers appear.
Expanding a leftover dictionary later
Because the unflattened value is a plain dictionary, you can pass a column of them back into json_normalize. Build a list from the column, normalize it, and join the result to the original frame.
df = pd.json_normalize(users, max_level=1)
geo_dicts = [g if isinstance(g, dict) else {} for g in df["address.geo"]]
geo = pd.json_normalize(geo_dicts).add_prefix("geo_")
geo.index = df.index
df = df.drop(columns="address.geo").join(geo)
print(df.columns.tolist())
# ['id', 'name', 'address.city', 'geo_lat', 'geo_lng']Two details in this code matter.
- The list comprehension replaces missing values with
{}. If some records had nogeokey, that cell would holdNaN, which is a float.json_normalizeraises an error when asked to flatten a non-dictionary item in the list. geo.index = df.indexkeeps the join correct ifdfdoesn't have a default0..n-1index. Without it,joinaligns on index labels, and rows could pair up wrongly or come out empty.
max_level and record_path
When you use record_path, max_level applies to the dictionaries inside the records that are being expanded. Lists are not touched by max_level, with or without record_path. Use record_path for lists.
orders = [
{
"order_id": 100,
"items": [
{"sku": "A1", "price": {"amount": 5.0, "currency": "USD"}},
{"sku": "B2", "price": {"amount": 3.5, "currency": "USD"}},
],
},
]
full = pd.json_normalize(orders, record_path="items", meta=["order_id"])
print(full.columns.tolist())
# ['sku', 'price.amount', 'price.currency', 'order_id']
shallow = pd.json_normalize(orders, record_path="items", meta=["order_id"], max_level=0)
print(shallow.columns.tolist())
# ['sku', 'price', 'order_id']
print(shallow["price"].iloc[0])
# {'amount': 5.0, 'currency': 'USD'}The items list is expanded into rows in both cases. max_level=0 only affects the dictionary inside each item.
Common errors and surprises
The behaviors below are the ones that most often confuse people.
| Symptom | Cause | Fix |
|---|---|---|
| A column holds `{'lat': ..., 'lng': ...}` and you expected two columns | `max_level` is lower than the depth of that dictionary | Raise `max_level`, or remove it |
| `max_level=1` leaves a dictionary you expected to be flattened | You counted from 1 at the root. Counting starts at 0, so level 1 expands only the first layer of dictionaries | Raise `max_level` by one |
| A column still holds a list | `max_level` never expands lists | Use `record_path`, or `explode` the column |
| `groupby` or `drop_duplicates` fails with an "unhashable type: 'dict'" error | The key column contains dictionaries | Flatten that column first, or convert it to a string with `.astype(str)` |
| Flattening the leftover column fails with an attribute or type error | Missing records left `NaN` in the cell | Replace non-dict values with `{}` before normalizing, as shown above |
| Different shapes between runs on different input | `max_level` fixes depth, but keys inside kept dictionaries can still vary | Inspect `df.columns` after loading, or flatten the leftover column explicitly |
Choosing a value
Pick max_level by looking at your data, not by guessing.
- Run
pd.json_normalize(data)once and printdf.columns.tolist(). - Look for groups of columns that share a long prefix and look like values rather than field names. These are candidates for being kept as a dictionary.
- Count the dots in the prefix before that group. That count is the
max_levelthat preserves it. Forscores.u101, there is one dot, so a limit that keepsscoreswhole ismax_level=0. - Rerun with that value and confirm the column count dropped as expected.
Keep in mind that one value of max_level applies to the whole document. If one branch should be flattened deeply and another kept shallow, a single call can't do both. Normalize the shallow structure, then expand the specific column afterward, as in the earlier section.
Exercise
A list of records looks like {"id": 1, "meta": {"tags": {"a": 1, "b": 2}, "owner": {"name": "Ada", "team": {"id": 7}}}}. What columns does pd.jsonnormalize(data, maxlevel=1) produce, and what type does each one hold? Which max_level would also produce a meta.owner.team.id column?
Show answer
With maxlevel=1 the columns are id, meta.tags, and meta.owner. The id column holds an int, and meta.tags and meta.owner each hold a dict ({'a': 1, 'b': 2} and {'name': 'Ada', 'team': {'id': 7}}). To get meta.owner.team.id you need maxlevel=3 (or None), because meta is level 1, owner is level 2, and team is level 3 and must be expanded to reach id. Anything below 3 leaves team as a dict.
Exercise
You normalize a list of records with maxlevel=1 and df["address.geo"] contains dicts for most rows but NaN for a few rows whose record had no geo key. You call pd.jsonnormalize(df["address.geo"].tolist()) and get an error. Why, and what is the fix?
Show answer
The list contains NaN, which is a float and not a dictionary, and json_normalize cannot flatten it. Replace each non-dict value with an empty dict first, for example [g if isinstance(g, dict) else {} for g in df["address.geo"]], then normalize that list. Set the resulting frame's index to df.index before joining it back so rows align.