Sub topic 10
Preventing column collisions with record_prefix and meta_prefix
Prerequisites
This chapter assumes you already know the following:
- How
pd.json_normalizeflattens nested objects into dotted column names. - How
record_pathexpands a list into one row per element. - How
metacopies parent fields onto those rows.
If any of these feel shaky, review the earlier chapters on record_path and meta first.
Why collisions happen
When you use record_path with meta, pandas builds the result from two sources. The first is the list of records you expanded. The second is the parent fields you asked to keep. Both sources become columns in the same table. Nothing forces them to use different names, and JSON often reuses names such as id, name, or type at several levels.
An order has an id. Each line item in that order may also have an id. If you expand items and ask for the order's id through meta, two columns want the name id.
pandas does not pick one silently. It stops with an error, so you never lose data without noticing. The cost is that your call fails until you say how to tell the two sources apart.
A dataset that collides
The examples in this chapter use one dataset. Order and item records both have an id. The customer object has an id too. Each item has a nested price object.
import pandas as pd
orders = [
{
"id": 100,
"customer": {"id": 1, "name": "Ada"},
"items": [
{"id": "A1", "qty": 2, "price": {"amount": 9.5}},
{"id": "B2", "qty": 1, "price": {"amount": 20.0}},
],
},
{
"id": 101,
"customer": {"id": 2, "name": "Grace"},
"items": [
{"id": "A1", "qty": 5, "price": {"amount": 9.5}},
],
},
]Now ask for the item rows plus the order's id:
try:
pd.json_normalize(orders, record_path="items", meta=["id"])
except ValueError as exc:
print(exc)
# Conflicting metadata name id, need distinguishing prefixThe message names the cause and the fix. The item columns are id, qty, and price.amount. The meta column is also id. pandas refuses to overwrite one with the other, so it raises ValueError.
Only the exact name matters. meta=[["customer", "id"]] would produce a column called customer.id, which does not clash with the item id. A collision happens only when the final column names are identical.
What the two prefixes do
Two keyword arguments add a string to the front of column names:
| Argument | Applies to | Default |
|---|---|---|
| `record_prefix` | Every column that comes from the expanded records | `None` (no prefix) |
| `meta_prefix` | Every column that comes from `meta` | `None` (no prefix) |
Both are plain string concatenation. pandas does not insert an underscore or a dot between the prefix and the name. If you want a separator, put it in the prefix yourself: "item_", not "item".
Both prefixes apply only when you use record_path. Without record_path, there is no second source of columns, so nothing can collide.
Fixing the collision
You can prefix either side or both. Prefixing one side is enough to resolve the clash.
Prefix only the meta columns
df = pd.json_normalize(
orders,
record_path="items",
meta=["id"],
meta_prefix="order_",
)
print(df.columns.tolist())
# ['id', 'qty', 'price.amount', 'order_id']The item id keeps its name, and the order's id becomes order_id. This is a good choice when the records are the main subject of the table. In this example, that means line items.
Prefix only the record columns
df = pd.json_normalize(
orders,
record_path="items",
meta=["id"],
record_prefix="item_",
)
print(df.columns.tolist())
# ['item_id', 'item_qty', 'item_price.amount', 'id']Here the order keeps id, and every item column gains item_. Note that price.amount became item_price.amount. The record prefix is applied after the records have been flattened, so it covers nested leaf columns as well. It goes in front of the whole dotted name, not in front of each part.
Prefix both sides
df = pd.json_normalize(
orders,
record_path="items",
meta=["id", ["customer", "id"], ["customer", "name"]],
record_prefix="item_",
meta_prefix="order.",
)
print(df.columns.tolist())
# ['item_id', 'item_qty', 'item_price.amount',
# 'order.id', 'order.customer.id', 'order.customer.name']
print(len(df))
# 3Every column now tells you where it came from. Prefixing both sides takes the most typing, but the table is the easiest to read later. Anyone who sees order.customer.name knows it is a parent field.
The result has three rows, one per item across both orders:
| item_id | item_qty | item_price.amount | order.id | order.customer.id | order.customer.name |
|---|---|---|---|---|---|
| A1 | 2 | 9.5 | 100 | 1 | Ada |
| B2 | 1 | 20.0 | 100 | 1 | Ada |
| A1 | 5 | 9.5 | 101 | 2 | Grace |
How the prefix meets a nested meta path
A nested meta path is a list of keys, such as ["customer", "name"]. pandas first joins the keys with sep to form customer.name. Then it adds meta_prefix once, in front of the joined name. The prefix is not repeated for each key.
This means sep and the prefixes work together. If you set sep="_", the joined path uses underscores. A matching prefix then keeps the naming consistent:
df = pd.json_normalize(
orders,
record_path="items",
meta=["id", ["customer", "name"]],
sep="_",
record_prefix="item_",
meta_prefix="order_",
)
print(df.columns.tolist())
# ['item_id', 'item_qty', 'item_price_amount', 'order_id', 'order_customer_name']sep also changed the flattened item column to price_amount, so it reads item_price_amount with one separator style throughout. Pick one style up front. A mix of dots and underscores makes later column selection error-prone.
Choosing where the prefix goes
The decision is mostly about which side you will use more often. The diagram shows a simple way to choose.
Two practical reasons to prefix both sides even when no collision exists:
- Future changes. APIs add fields. If the item objects gain a
customerkey next month, a call that worked today may start failing. Prefixes protect you from that. - Joins. If you later merge this table with another one, the prefixes show which columns are item data and which are order data, and they avoid
_xand_ysuffixes frommerge.
Gotchas
- Prefixes can still collide. If
record_prefix="x_"and the meta key is literallyx_id, the final names match and you get the sameValueError. This is rare, but it explains the error if you see it after adding a prefix. - Prefix text is not trimmed or validated.
meta_prefix="order"givesorderid, notorder_id. Check the column list after your first run. - The prefix is not a rename. The prefix is applied while the table is built. If you need different names afterward, see the chapter on cleaning up the DataFrame.
- No prefix means no protection from unrelated overlaps. A collision only raises an error between the meta and record sides. Two columns that overlap inside a single flattened record are already combined by the flattening step itself.
errors="ignore"does not help here. That option controls missing meta keys, not duplicate names. A collision still raises.
Summary
record_pathplusmetabuilds one table from two sources, and identical column names between them raiseValueError: Conflicting metadata name ..., need distinguishing prefix.record_prefixis added to every record column, including flattened nested ones.meta_prefixis added to every meta column, in front of the joined path.- Neither prefix adds a separator on its own. Include it in the string.
- Prefix one side to fix a collision, or both sides to make the table self-describing.
Exercise
Given data = [{"id": 7, "tags": [{"id": "x", "label": "red"}, {"id": "y", "label": "blue"}]}], write a pd.json_normalize call that expands tags into rows and keeps the parent id without raising an error, so the columns are ['id', 'label', 'parent_id'].
Show answer
Use meta_prefix on the parent side only: pd.json_normalize(data, record_path="tags", meta=["id"], meta_prefix="parent_"). The tag id keeps its name, label is unchanged, and the parent id becomes parent_id. Without the prefix, both sources would produce id and pandas would raise ValueError.
Exercise
Using the orders data from this chapter, you call pd.json_normalize(orders, record_path="items", meta=[["customer", "name"]], record_prefix="item_", meta_prefix="cust."). What is the full list of column names, and why does no collision occur even though the original data has several id keys?
Show answer
The columns are ['item_id', 'item_qty', 'item_price.amount', 'cust.customer.name']. The meta path ["customer", "name"] is joined into customer.name and then the prefix cust. is placed in front once. No collision occurs because the only meta field requested is customer.name, which no item column shares. The order id and customer.id were never requested, and the record prefix also makes every item column distinct.
Exercise
A teammate sets record_prefix="item" (no underscore) and finds columns such as itemid and itemqty. What went wrong, and how do you fix it?
Show answer
pandas concatenates the prefix with the column name and adds no separator. Fix it by including the separator in the string: record_prefix="item_". This gives item_id and item_qty.