Sub topic 7
Why lists stay as list values in a column
This chapter assumes you can call pd.json_normalize on a list of dictionaries and read the dotted column names it produces. You should also know the difference between a missing key and a key whose value is None.
json_normalize flattens nested objects into columns. It does not flatten lists. Any list value goes into a single cell as a Python list. This chapter explains why, how to recognise the result, and what to do about it.
The behavior
Start with records where one field is a list and one record lacks that field:
import pandas as pd
posts = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced"},
{"id": 3, "title": "Drafts", "tags": []},
]
df = pd.json_normalize(posts)
print(df.columns.tolist())
# ['id', 'title', 'tags']
print(df["tags"].iloc[0])
# ['python', 'pandas']
print(df["tags"].map(type).tolist())
# [<class 'list'>, <class 'float'>, <class 'list'>]The tags column has dtype object. Rows 0 and 2 hold real Python lists. Row 1 holds nan, a float, because that record had no tags key. The column therefore mixes two types.
Why the library does not flatten lists
A nested object has a fixed set of keys, so each key can become a column. A list has no fixed size, so there is no obvious flat layout for it. There are two ways to flatten one, and each changes the table.
| Option | Result | Cost |
|---|---|---|
| One column per position (`tags.0`, `tags.1`, ...) | Number of columns depends on the longest list | Ragged, mostly empty columns. Position carries no meaning. |
| One row per element | Parent values repeat on every row | The row count no longer matches the record count. |
The first option makes the schema depend on the data. The second changes what one row means. Either choice can silently alter the result, so json_normalize does neither by default. It keeps one row per input record and leaves the list intact. You ask for the row-per-element layout explicitly with record_path, which the next chapter covers.
Lists nested inside objects
The rule applies at every depth. json_normalize still flattens the surrounding objects, and it stops at the list:
import pandas as pd
events = [
{"id": 1, "meta": {"source": "web", "labels": ["new", "paid"]}},
{"id": 2, "meta": {"source": "app", "labels": ["new"]}},
]
df = pd.json_normalize(events)
print(df.columns.tolist())
# ['id', 'meta.source', 'meta.labels']
print(df["meta.labels"].tolist())
# [['new', 'paid'], ['new']]The meta.labels column carries the dotted name from the object path, but each cell still holds a list.
Lists of dictionaries stay as lists of dictionaries
A list of records is still a list. Without record_path, the dictionaries inside it are not flattened either:
import pandas as pd
orders = [
{
"order_id": 100,
"customer": {"id": 1, "name": "Ada"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}],
},
{
"order_id": 101,
"customer": {"id": 2, "name": "Grace"},
"items": [{"sku": "A1", "qty": 5}],
},
]
df = pd.json_normalize(orders)
print(df.columns.tolist())
# ['order_id', 'customer.id', 'customer.name', 'items']
print(df["items"].iloc[0][0])
# {'sku': 'A1', 'qty': 2}
print(len(df))
# 2The customer object is flattened, so customer.id and customer.name appear as columns. The items list is untouched, and the table has two rows, one per order. If you expected one row per item, this is the symptom that tells you to use record_path.
Empty list versus missing key
The two cases look similar but mean different things in the source data.
"tags": []means the field exists and has no elements. The cell holds[].- A missing
tagskey means the field was never sent. The cell holdsnan.
You can tell them apart, but isna alone does not do it, because [] is not NA:
import pandas as pd
posts = [
{"id": 1, "tags": ["python", "pandas"]},
{"id": 2},
{"id": 3, "tags": []},
]
df = pd.json_normalize(posts)
print(df["tags"].isna().tolist())
# [False, True, False]
print(df["tags"].str.len().tolist())
# [2.0, nan, 0.0].str.len() works on list cells as well as strings. It returns the list length, and NaN where the key was missing. The result is float because of the NaN.
A frequent bug is a membership test such as "python" in df["tags"].iloc[1]. On the missing row that tests "python" in nan, which raises TypeError. Guard for it:
import pandas as pd
df = pd.json_normalize([{"id": 1, "tags": ["python"]}, {"id": 2}])
has_python = df["tags"].map(lambda t: isinstance(t, list) and "python" in t)
print(has_python.tolist())
# [True, False]Finding which columns still hold lists
After flattening an unfamiliar payload, check which columns still contain lists. Do this before you write analysis code:
import pandas as pd
df = pd.json_normalize([
{"id": 1, "tags": ["a", "b"], "owner": {"name": "Ada"}},
{"id": 2, "tags": ["c"], "owner": {"name": "Grace"}},
])
list_cols = [
col for col in df.columns
if df[col].map(lambda v: isinstance(v, list)).any()
]
print(list_cols)
# ['tags']Each column you find is a decision point. You can leave it, expand it to rows, spread it to columns, or drop it.
What goes wrong when lists stay in cells
Lists are valid cell values, but many pandas operations assume hashable, scalar cells.
df.drop_duplicates()raisesTypeError: unhashable type: 'list', because pandas must hash each cell to compare rows. Drop or convert the list columns first, or pass asubsetof scalar columns.groupbyon a list column fails for the same reason. Grouping by other columns works.- Writing to CSV stores each list as its Python text form, for example
['python', 'pandas']. Reading it back gives you a string, not a list. df["tags"] == "python"compares a whole list to a string and is alwaysFalse. It does not check membership.
Three ways to deal with a list column
Expand to one row per element
DataFrame.explode turns each list element into its own row and repeats the other columns. The row count changes, as in the table above.
import pandas as pd
df = pd.json_normalize([
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced"},
])
long_df = df.explode("tags", ignore_index=True)
print(long_df)
# id title tags
# 0 1 Intro python
# 1 1 Intro pandas
# 2 2 Advanced NaNA missing key or an empty list becomes one row with NaN, so no record disappears.
Spread to one column per position
If lists are short and position matters, build columns from the list values. Work on the non-missing cells and join back by index:
import pandas as pd
df = pd.json_normalize([
{"id": 1, "tags": ["python", "pandas"]},
{"id": 2},
])
present = df["tags"].dropna()
wide = pd.DataFrame(present.tolist(), index=present.index).add_prefix("tag_")
df = df.join(wide)
print(df.columns.tolist())
# ['id', 'tags', 'tag_0', 'tag_1']
print(df["tag_1"].tolist())
# ['pandas', nan]Use this only when the maximum list length is small and bounded. A list of 500 elements would create 500 columns.
Expand with record_path
When the list holds dictionaries, record_path expands it into rows and flattens each dictionary into columns in one step. meta then carries the parent fields along. That is the approach for lists of records, and the next chapter covers it.
Choosing between them
| Situation | Reasonable choice |
|---|---|
| List of dictionaries (line items, comments) | `record_path` with `meta` |
| List of plain values you want to count or filter by | `explode`, or keep the list and use `.str.len()` |
| Short fixed-size list where position matters (coordinates) | Spread to columns |
| List you will never analyse | Leave it, but drop it before `drop_duplicates` or CSV export |
Summary
json_normalize flattens objects because their keys give fixed column names. It leaves lists in cells because flattening them would either make the column count depend on the data or change the number of rows. Missing keys give NaN and empty lists give [], and these are different values. Find list columns early, then choose record_path, explode, positional columns, or no change.
Exercise
You run pd.jsonnormalize on 50 order records and get 50 rows, but each order has several line items and you wanted one row per item. The columns include 'orderid' and 'items'. What is happening, and what should you change?
Show answer
The 'items' field is a list, so jsonnormalize stores each whole list in one cell and keeps one row per order. To get one row per item, pass recordpath="items" and add meta=["order_id"] so the order ID is copied onto each item row.
Exercise
A DataFrame has a 'tags' column built from json_normalize. Row A has the key missing in the source, and row B has "tags": []. What values do the two cells hold, and which expression returns True only for row A?
Show answer
Row A holds nan (a float) and row B holds an empty list []. df["tags"].isna() returns True only for row A, because an empty list is not treated as NA.
Exercise
Why does df.drop_duplicates() raise a TypeError on a DataFrame with a list column, and how can you avoid the error without changing the data?
Show answer
pandas hashes cell values to find duplicate rows, and lists are unhashable. Pass a subset of scalar columns, for example df.drop_duplicates(subset=["id"]), or drop the list columns before deduplicating.