Sub topic 12
Cleaning up the flattened DataFrame
This chapter assumes you can call pd.json_normalize on a list of dicts and know that nested keys become dotted column names. After flattening, the table is usually not ready to use. The column names contain dots, and every value may still be a string, because JSON text often stores numbers as quoted strings. This chapter covers the two cleanup steps that usually follow: renaming columns and converting dtypes.
Why cleanup is needed
json_normalize copies values as it finds them. It does not guess types or tidy names. Two problems follow from that.
- Dotted names such as
address.geo.latcannot be used as attributes (df.address.geo.latfails). They also need quotes inDataFrame.query. - A value stored as
"51.5"in the JSON becomes a Python string in anobjectcolumn. Sums, comparisons, and plots then behave wrongly or raise errors.
Renaming columns
If you only want a different separator, pass sep to json_normalize instead. When the data is already flattened, use a vectorized string method on the column index.
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)
df["id"] = pd.to_numeric(df["id"])
df["address_geo_lat"] = pd.to_numeric(df["address_geo_lat"])
print(df.columns.tolist())
# ['id', 'address_city', 'address_geo_lat']
print(df.dtypes.tolist())
# [dtype('int64'), dtype('O'), dtype('float64')]Pass regex=False here. Without it, older pandas versions treat "." as a regular expression that matches every character, and you get a column of underscores.
To shorten only some names, use rename with a dictionary. Columns not listed keep their names.
Converting dtypes
pd.to_numeric converts a column of strings to int64 or float64. By default it raises a ValueError on any value it cannot parse. Pass errors="coerce" to turn bad values into NaN instead. This also matters for columns that gained NaN from missing keys, because an integer column with NaN becomes float64.
import pandas as pd
raw = [
{"id": "1", "price": "9.99", "address": {"city": "London"}},
{"id": "2", "price": "n/a", "address": {"city": "Paris"}},
]
df = pd.json_normalize(raw)
df = df.rename(columns={"address.city": "city"})
df["id"] = pd.to_numeric(df["id"])
df["price"] = pd.to_numeric(df["price"], errors="coerce")
print(df)
# id price city
# 0 1 9.99 London
# 1 2 NaN Paris
print(df.dtypes.tolist())
# [dtype('int64'), dtype('float64'), dtype('O')]Other useful conversions:
| Goal | Call |
|---|---|
| Strings to numbers | `pd.to_numeric(col, errors="coerce")` |
| Strings to timestamps | `pd.to_datetime(col, errors="coerce")` |
| Repeated labels to a compact type | `col.astype("category")` |
| Nullable integers that allow missing values | `col.astype("Int64")` |
Common errors
- Forgetting that dtypes did not change. Print
df.dtypesafter flattening. A column that looks numeric but showsobjectstill holds strings. - Renaming before checking for collisions. If two dotted names map to the same new name, you get duplicate columns. Use
record_prefixormeta_prefixearlier if the names could clash. - Using
errors="coerce"without looking at the result. It hides bad data. Count the newNaNvalues withdf["price"].isna().sum()and compare with the count before conversion. - Expecting list columns to convert. A cell holding a list, such as
tags, is not touched byto_numeric. Expand it into rows first.
Exercise
A flattened DataFrame has a column stats.score that holds the strings "10", "7", and "missing". Write the two lines that rename it to score and convert it to a numeric column where "missing" becomes NaN.
Show answer
df = df.rename(columns={"stats.score": "score"}) df["score"] = pd.to_numeric(df["score"], errors="coerce")