Sub topic 4
How nested keys become column names, and changing the separator
This chapter assumes you can read Python dictionaries, have called pd.json_normalize on a list of dicts, and can inspect df.columns. It covers how the function names the columns it creates and how to change that naming.
The naming rule
json_normalize walks each record and turns every nested object into columns. Each column name is the path of keys from the top of the record down to the value, joined by a separator. The default separator is a dot.
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 = pd.json_normalize(users)
print(df.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo.lat', 'address.geo.lng']Top-level keys such as id keep their own names. The value 51.5 sits two objects deep, under address and then geo, so its column is address.geo.lat.
Changing the separator with sep
The sep argument sets the string placed between key names.
df_sep = pd.json_normalize(users, sep="_")
print(df_sep.columns.tolist())
# ['id', 'name', 'address_city', 'address_geo_lat', 'address_geo_lng']Any string works, such as "__" or "/". The separator applies only to names built from nested objects. Keys that were already at the top level are unchanged.
Why you might change it
A dot in a column name is legal, but it causes friction in day-to-day pandas code:
- Attribute access fails.
df.address.cityraises an error, so you must writedf["address.city"]. DataFrame.query()andeval()need backticks around such names, as in `df.query("address.city== 'London'")`.- Some databases and export formats reject dots in column names.
With sep="_" the names are valid Python identifiers, so df.address_city works.
| Goal | Choice |
|---|---|
| Keep the key path obvious and reversible | Default `"."` |
| Use attribute access and `query()` without backticks | `sep="_"` |
| Write to SQL or a format that rejects dots | `sep="_"` or `"__"` |
Watch for collisions
Underscores are common inside real JSON keys. If a record has both a top-level key address_city and a nested address object with a city key, sep="_" produces the same name for both. One value can overwrite the other without any error. Check your keys before you choose an underscore, or use a rarer separator such as "__". The dot is also the safest default because dots rarely appear in JSON keys.
The sep argument does not help when two different sources produce the same column name, such as record fields and parent fields. A later chapter covers that case with prefixes.
Renaming afterward
You can also keep the default and rename later. This is useful when you want to inspect the dotted names first.
df = pd.json_normalize(users)
df.columns = df.columns.str.replace(".", "_", regex=False)
print(df.columns.tolist())
# ['id', 'name', 'address_city', 'address_geo_lat', 'address_geo_lng']Pass regex=False here. Without it, older pandas versions treat "." as a regular expression that matches any character, which would replace every character in the names.
Exercise
A record contains the key "user_name" at the top level and also {"user": {"name": "Ada"}}. What goes wrong if you call pd.json_normalize(data, sep="_"), and what can you do about it?
Show answer
Both keys produce the column name user_name, so one value can overwrite the other and you may lose data. Use a separator that does not appear in your keys, such as sep="__", or keep the default "." and rename the columns afterward.
Exercise
Given df = pd.json_normalize(users) from this chapter, how do you select the city column, and how does that change with sep="_"?
Show answer
With the default separator you write df["address.city"], because the dot makes attribute access fail. With sep="_" the column is address_city, so both df["address_city"] and df.address_city work.