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 dicts and read the dotted column names it produces. You should also know that JSON objects become Python dicts and JSON arrays become Python lists.
What json_normalize does with each value type
json_normalize treats the two container types differently:
- A dict value is flattened. Each key inside it becomes its own column, and the key path is joined with the separator.
- A list value is not flattened. It is stored in the cell as one Python list object.
The diagram shows the decision it makes for each value.
Seeing it happen
The code below uses two blog posts. The first has a tags list. The second has no tags key.
import pandas as pd
posts = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced"},
]
df = pd.json_normalize(posts)
print(df.columns.tolist())
# ['id', 'title', 'tags']
print(df["tags"].iloc[0])
# ['python', 'pandas']
print(df["tags"].iloc[1])
# nanThe result has one row per post, and tags is still a single column. The first cell holds the whole list. The second cell holds NaN because that record has no tags key. This is the same missing-key behavior you saw in the previous chapter.
Why the library does not flatten lists
Flattening a list would force the library to guess the table's shape, and no guess is safe.
- Unknown column count. Dict keys are names, so
address.cityis a stable column. List positions are not stable names. One post may have two tags and another may have twenty. Columns liketags.0andtags.1would differ from record to record. - Rows or columns. A list could become extra columns, or extra rows. Those two results describe different tables, and the library cannot tell which one you want.
- Row count changes. Turning list elements into rows changes what one row means. That choice should be explicit, so it is controlled by
record_path, which the next chapter covers.
Working with list cells
A list cell is an ordinary Python object, so it behaves differently from a number or string. Two things catch people out.
First, the .str accessor also works on list cells for a few operations, such as length and indexing:
print(df["tags"].str.len().tolist())
# [2.0, nan]
print(df["tags"].str[0].tolist())
# ['python', nan]The NaN cell stays NaN, and the lengths become floats because of it.
Second, you can find every column that holds lists before you decide how to handle them:
list_cols = [
col for col in df.columns
if df[col].map(lambda v: isinstance(v, list)).any()
]
print(list_cols)
# ['tags']A column that still contains lists is usually a sign that the data has more structure to unpack.
Choosing what to do with a list column
Your choice depends on what the list contains:
| List contains | Typical goal | Approach |
|---|---|---|
| Dicts (records), such as order items | One row per element | `record_path`, next chapter |
| Simple values, such as tags | One row per value | `df.explode("tags")` |
| Anything, and you only need a summary | A count or a joined string | Keep the list and use `.str.len()` or `.str.join(", ")` |
| Anything, and you do not need it | A narrower table | Drop the column |
If you leave the list in place, remember that the column is not ready for analysis yet.
Exercise
You call pd.json_normalize on records that each contain a "phones" key holding a list such as ["555-1", "555-2"]. What does the phones column contain, and why does the library not create one column per phone number?
Show answer
The column contains the whole Python list in each cell, with NaN for records that lack the key. The library does not split it because list positions are not stable names, so the number of columns would vary by record. It also cannot know whether you want the elements as columns or as rows, so you choose explicitly with record_path or explode.