Sub topic 12
Cleaning up the flattened DataFrame
json_normalize gives you a flat table, but it rarely gives you a finished one. Column names contain dots, numbers may still be strings, and some cells hold lists or None. This chapter covers the steps that usually follow flattening: renaming columns, converting dtypes, handling missing values, and dealing with leftover lists.
It assumes you can call pd.json_normalize with sep, record_path, and meta, and that you know basic pandas operations such as assigning to df["col"] and using the .str accessor.
Why cleanup is a separate step
json_normalize decides the table's shape. It does not decide its names or types. It copies each value as Python parsed it, so you get these side effects:
- Nested keys become names like
address.geo.lat. Dots in a name stop you from using attribute access (df.address.geo.latfails) and force backticks indf.query. - A JSON string stays a string, even when it looks like
"51.5". The column has dtypeobject. - A key missing from some records becomes
NaN. A JSONnullbecomesNone. Both are missing values, but they sit inobjectcolumns until you convert them. - A list or dict that was not flattened stays inside the cell as a Python object.
Do cleanup last. First get the shape right with record_path, meta, and max_level. Then rename and convert, so you only clean the columns you keep.
Renaming columns
The simplest fix is to choose a separator when you flatten. sep="_" produces address_geo_lat directly. That works if you know the name you want in advance. If you already have a DataFrame with dotted names, rename afterwards.
Replace the dots in every name
import json
import pandas as pd
text = '[{"id": "1", "address": {"city": "London", "geo": {"lat": "51.5"}}}]'
data = json.loads(text)
df = pd.json_normalize(data)
df.columns = df.columns.str.replace(".", "_", regex=False)
print(df.columns.tolist())
# ['id', 'address_city', 'address_geo_lat']Pass regex=False. In older pandas versions, str.replace treated the pattern as a regular expression by default, and a bare . matches any character. That would turn every name into underscores. With regex=False the dot is literal on all versions.
Rename selected columns with a mapping
When you want short, specific names, use rename:
df = df.rename(columns={"address_city": "city", "address_geo_lat": "lat"})
print(df.columns.tolist())
# ['id', 'city', 'lat']rename ignores keys that do not exist, so a typo in the mapping fails silently. Print df.columns.tolist() afterwards to confirm.
Keep only the last part of the path
To drop the parent path from every name, split from the right:
df = pd.json_normalize(data)
df.columns = [c.rsplit(".", 1)[-1] for c in df.columns]
print(df.columns.tolist())
# ['id', 'city', 'lat']
print(df.columns.is_unique)
# TrueThis is risky. If the JSON has both id and customer.id, both columns become id, and df["id"] returns a two-column DataFrame instead of a Series. Always check df.columns.is_unique after a bulk rename.
Converting dtypes
json.loads preserves JSON types: numbers become int or float, true becomes True, and strings stay strings. Conversion is needed mainly when the API sends numbers, dates, or booleans as strings, or when missing values force a column to a wider type.
Here is a larger example with all of those problems:
import pandas as pd
rows = [
{"id": "1", "signup": "2024-03-01", "active": "true", "visits": "12",
"address": {"city": "London", "geo": {"lat": "51.5"}}},
{"id": "2", "signup": "2024-03-15", "active": "false", "visits": None,
"address": {"city": "New York", "geo": {"lat": "40.7"}}},
]
df = pd.json_normalize(rows, sep="_")
df["id"] = pd.to_numeric(df["id"])
df["visits"] = pd.to_numeric(df["visits"]).astype("Int64")
df["active"] = df["active"].map({"true": True, "false": False}).astype("boolean")
df["signup"] = pd.to_datetime(df["signup"])
df["address_geo_lat"] = pd.to_numeric(df["address_geo_lat"])
print(df[["id", "visits", "active", "signup", "address_geo_lat"]].dtypes)
# id int64
# visits Int64
# active boolean
# signup datetime64[ns]
# address_geo_lat float64On newer pandas versions the datetime unit may differ from ns.
Each conversion solves a different problem:
pd.to_numericparses strings intoint64orfloat64. It picks the narrowest type that fits.astype("Int64")uses pandas' nullable integer type, with a capitalI. A plainint64column cannot hold missing values. Without this step,visitswould stayfloat64(12.0,NaN).mapplusastype("boolean")turns text flags into booleans that can also hold<NA>. If any value is missing from the mapping dict,mapproducesNaN, which is why the nullable type is useful here.pd.to_datetimeparses date strings into real timestamps, so sorting and date arithmetic work.
Bad values: raise or coerce
pd.to_numeric and pd.to_datetime raise an error on the first value they cannot parse. Pass errors="coerce" to turn bad values into missing values instead:
s = pd.Series(["1", "n/a", "3"])
print(pd.to_numeric(s, errors="coerce").tolist())
# [1.0, nan, 3.0]Coercion hides data problems. After coercing, count the new missing values and compare with the count before. If the number grew, look at which source values failed:
before = s.isna().sum()
converted = pd.to_numeric(s, errors="coerce")
failed = s[converted.isna() & s.notna()]
print(before, failed.tolist())
# 0 ['n/a']Convert many columns at once
If a group of columns needs the same treatment, loop over names instead of repeating lines:
numeric_cols = ["id", "visits", "address_geo_lat"]
df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric, errors="coerce")df.convert_dtypes() is a shortcut that infers nullable types for every column. It does not parse strings into numbers or dates, so it complements the conversions above and does not replace them.
Missing values after flattening
A missing key and an explicit null both end up as missing values, but their representation depends on the column:
| Source | Column dtype | Cell value |
|---|---|---|
| Key absent in some records, numbers elsewhere | `float64` | `NaN` |
| Key absent in some records, strings elsewhere | `object` | `NaN` |
| JSON `null` in a column of strings | `object` | `None` |
| Nullable dtype after `astype("Int64")` | `Int64` | `<NA>` |
Use df.isna(), df.fillna(...), and df.dropna(subset=[...]). They treat NaN, None, and <NA> the same way, so you do not need to compare against None yourself. Choose a fill value only when it has a meaning. Filling a missing visits with 0 claims the user had no visits, which may not be true.
Lists and dicts left in cells
When a record contains a list that you did not expand with record_path, the cell holds a Python list. Missing keys give NaN, as covered earlier in this tutorial. If you want one row per list element after the fact, use explode:
posts = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced"},
]
df = pd.json_normalize(posts)
df = df.explode("tags", ignore_index=True)
print(df)
# id title tags
# 0 1 Intro python
# 1 1 Intro pandas
# 2 2 Advanced NaNexplode repeats every other column for each list element, so the row count grows. Row 2 has NaN instead of a list, and explode keeps it as a single row. An empty list [] also becomes one row with a missing value. Only the second example below appears in some cleaned data, so check for both cases.
If you only need to know something about a list, you may not need extra rows. df["tags"].str.len() works on list cells, and df["tags"].str[0] takes the first element. The .str accessor handles lists as well as strings, and it gives NaN for missing cells.
A dict left in a cell (for example after max_level=1) can be expanded into columns with pd.json_normalize(df["address.geo"].dropna().tolist()). Join the result back to df by index if you need it alongside the other columns.
A cleanup order that works
Renaming first means every later line uses the short names. Checking uniqueness immediately catches collisions before they cause confusing errors. Converting dtypes comes before filling missing values, because fillna(0) on a column of strings would mix types.
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| `df["id"]` returns a DataFrame | Two columns share the same name after renaming | Use a fuller name, or rename with an explicit mapping |
| `ValueError: Unable to parse string` | `to_numeric` hit a non-numeric string | Use `errors="coerce"` and inspect the failures |
| Integer column shows `12.0` | A missing value forced `float64` | Convert with `astype("Int64")` |
| `df.address.city` raises `AttributeError` | The column name has a dot | Use `sep="_"` or rename the columns |
| `df.query("address.city == 'London'")` fails | The dot is read as attribute access | Wrap the name in backticks, or rename first |
| Row count jumps after `explode` | One row is created per list element | Expected. Check with `len(df)` before and after |
Exercises
Exercise
A DataFrame from pd.json_normalize(data) has the columns order.id, order.total, and customer.id. All values are strings. You want the names order_id, order_total, and customer_id, with order_total as a float where unparseable values become missing. Which steps do you run, and in what order?
Show answer
First rename: df.columns = df.columns.str.replace(".", "_", regex=False). Then check df.columns.is_unique, which should be True. Then convert: df["order_total"] = pd.to_numeric(df["order_total"], errors="coerce"). You could also pass sep="_" to json_normalize and skip the first step.
Exercise
After pd.to_numeric(df["visits"], errors="coerce"), the column has 40 missing values, but only 3 were missing before the call. What does this mean, and how do you find the cause?
Show answer
37 values could not be parsed as numbers, and coercion silently turned them into missing values. To find them, compare against the original column: failed = df["visits"][converted.isna() & df["visits"].notna()], where converted is the result of to_numeric. Inspect failed.unique() to see the bad strings, then fix them (for example by stripping commas) before converting.