Sub topic 10
Preventing column collisions with record_prefix and meta_prefix
This chapter assumes you can call pd.json_normalize with record_path and meta, and that you know how nested keys become dotted column names. Here you will see what goes wrong when a record field and a parent field share a name, and how two prefix arguments fix it.
The collision problem
record_path expands a list into rows. meta copies parent fields onto those rows. Both sets of fields end up as columns in the same DataFrame. If a field inside the list has the same name as a field in meta, pandas cannot keep both under one name.
Consider orders where each order has an id, and each item also has an id.
import pandas as pd
orders = [
{"id": 100, "items": [{"id": "A1", "qty": 2}, {"id": "B2", "qty": 1}]},
{"id": 101, "items": [{"id": "A1", "qty": 5}]},
]
try:
df = pd.json_normalize(orders, record_path="items", meta=["id"])
except ValueError as err:
print(err)pandas raises a ValueError saying the conflicting column name id is already present. The message suggests using record_prefix or meta_prefix. Without one of them, the call fails instead of silently overwriting a column.
Adding a prefix to record columns
record_prefix is a string placed in front of every column that comes from the record_path list.
df = pd.json_normalize(
orders,
record_path="items",
meta=["id"],
record_prefix="item_",
)
print(df.columns.tolist())
# ['item_id', 'item_qty', 'id']
print(df)
# item_id item_qty id
# 0 A1 2 100
# 1 B2 1 100
# 2 A1 5 101The item columns are now item_id and item_qty. The meta column keeps its plain name id, so the two no longer clash.
Note that the prefix applies to every record column, not only the one that collides. That keeps naming consistent, but it also renames columns that were never a problem.
Adding a prefix to meta columns
meta_prefix does the same for the columns that come from meta. Use it when you would rather leave the record columns alone.
df = pd.json_normalize(
orders,
record_path="items",
meta=["id"],
meta_prefix="order_",
)
print(df.columns.tolist())
# ['id', 'qty', 'order_id']Now the item's id stays as id, and the order's id becomes order_id.
Using both prefixes together
You can pass both arguments in the same call. This is the clearest option when the table will be read by other people, because every column states where it came from.
df = pd.json_normalize(
orders,
record_path="items",
meta=["id"],
record_prefix="item.",
meta_prefix="order.",
)
print(df.columns.tolist())
# ['item.id', 'item.qty', 'order.id']The prefix is plain text, so the separator is whatever you type. It is independent of the sep argument. A prefix such as "item." does not change how sep joins nested keys, and sep does not insert a separator after your prefix.
How the pieces fit
Common mistakes
- Forgetting that prefixes need
record_path.record_prefixandmeta_prefixonly matter when you expand a list. Withoutrecord_path, there is no second source of columns to collide. - Expecting a prefix to add a separator. The string is used exactly as given.
record_prefix="item"producesitemid, notitem_id. - Prefixing when you could rename. If you only need different names after the fact,
df.rename(columns=...)works too. Prefixes are better when the collision would otherwise stop the call from running at all.
Exercise
Exercise
Each shipment has a top-level "id" and a "packages" list. Each package also has an "id" and a "weight". Write a jsonnormalize call that expands "packages" into rows, keeps the shipment id, and returns the columns ['pkgid', 'pkgweight', 'shipmentid'].
Show answer
Use both prefixes: pd.jsonnormalize(shipments, recordpath="packages", meta=["id"], recordprefix="pkg", metaprefix="shipment"). recordprefix renames id and weight to pkgid and pkgweight, and metaprefix renames the meta column id to shipment_id, so no names collide.