Sub topic 6
Splitting and extracting into columns
This chapter assumes you know basic Python strings, regular expression syntax, and how to create and index a pandas Series or DataFrame. It also assumes you have met the string dtype and the .str accessor from earlier chapters.
Real text columns often pack several facts into one cell, such as a full name or a code like id-042. Pandas gives you two main tools to pull those facts into separate columns: str.split and str.extract. Both belong to the .str accessor, and both keep missing values as <NA> on a string column.
Splitting one column into many
str.split cuts each string at a separator. By default it returns a Series where each cell holds a list. With expand=True it returns a DataFrame instead, with one column per piece. That lets you assign the pieces to new columns in one statement.
import pandas as pd
df = pd.DataFrame(
{"name": ["Ada Lovelace", "Alan Turing"]},
dtype="string",
)
df[["first", "last"]] = df["name"].str.split(" ", n=1, expand=True)
print(df)The argument n=1 limits the split to one cut. Everything after the first space stays together in the second piece. This matters for names like Mary Ann Smith, where you would otherwise get three pieces and a shape mismatch on assignment.
What can go wrong with split
- If rows produce different numbers of pieces, the DataFrame is as wide as the longest row. Shorter rows are padded with missing values.
- If the number of new column names does not match the number of columns produced, the assignment raises an error. Setting
nmakes the width predictable. - A missing entry stays missing in every output column.
- In older pandas versions, a single-character
patis treated as a literal, but a longer one is treated as a regular expression. Passregex=Falseto be explicit.
Extracting with a regular expression
str.split works when a separator exists. When the structure is a pattern, use str.extract. It applies a regular expression to each string and returns the text matched by each capture group (the parts in parentheses). Where there is no match, you get <NA>.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
print(s.str.extract(r"id-(\d+)", expand=False))
print(s.str.replace(".", "-", regex=False))With one capture group and expand=False, the result is a Series. With expand=True, which is the default, it is always a DataFrame. With several groups, you always get a DataFrame, one column per group.
The second line of the example shows why you should choose literal or regex matching explicitly. In a regular expression, . matches any character. With regex=False, it matches only a real dot. Because "id-001" contains no dots, the output is unchanged.
Named groups give named columns
Name a group with (?P<name>...) and the column takes that name. This is clearer than numbered columns.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
parts = s.str.extract(r"(?P<prefix>[a-z]+)-(?P<number>\d+)")
print(parts)Rows that do not match, such as unknown, are <NA> in every column. The extracted columns are string, so you must convert the numbers yourself.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
number = s.str.extract(r"id-(\d+)", expand=False).astype("Int64")
print(number)The nullable Int64 dtype keeps the missing entry as <NA>. A plain int conversion would fail on it.
Choosing between split and extract
| Situation | Use |
|---|---|
| Fixed separator, every row has the same shape | `str.split(..., expand=True)` |
| Separator may repeat and you want only the first cut | `str.split(..., n=1, expand=True)` |
| Pieces follow a pattern, some rows may not match | `str.extract` |
| You need every match in a cell, not only the first | `str.extractall` |
str.extractall returns a DataFrame with a MultiIndex. The first level is the original row and the second level is the match number.
Exercise
A string column holds the values "x-12", "y-7", and a missing entry. You run s.str.extract(r"-(\d+)", expand=False). What does the result contain, and what must you do to get integers that keep the missing entry?
Show answer
The result is a string Series with "12", "7", and <NA>. Call .astype("Int64") on it. The nullable Int64 dtype stores the missing entry as <NA>, while a plain int dtype cannot hold it.