Sub topic 6
Splitting and Extracting into Columns
This chapter assumes you can create a Series or DataFrame, know what a dtype is, and can read a basic regular expression. It also assumes you have met the string dtype and the .str accessor from earlier chapters. The examples use pandas 2.x with dtype="string". They behave the same under the default str dtype in pandas 3, except where noted.
Text columns often pack several facts into one value, such as "Ada Lovelace", "id-042", or "2026-12-01T13:49". This chapter covers how to turn one text column into several columns. There are two tools. str.split and its relatives cut a string at a separator. str.extract pulls out the parts that match a regex.
Splitting at a separator
str.split cuts each string wherever a separator appears. By default it returns a Series where each element is a list of pieces. That shape is rarely what you want to keep.
import pandas as pd
s = pd.Series(["a-b-c", "d-e", None], dtype="string")
print(s.str.split("-"))The result has dtype object, because each element is a Python list. The missing entry stays <NA>. Lists inside cells are hard to filter or aggregate, so most code passes expand=True. That returns a DataFrame with one column per piece.
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) name first last
0 Ada Lovelace Ada Lovelace
1 Alan Turing Alan TuringThe n=1 argument limits the split to one cut, so you get at most two pieces. Without n, a name such as "Grace Brewster Murray Hopper" would produce four pieces and the two-column assignment would fail.
On a string column, the expanded columns also have dtype string. On an object column they are object, and missing values may appear as None or NaN.
Choosing the cut from the right
str.rsplit works like split but counts from the end. It is the right choice when the last piece is the one you know is stable.
import pandas as pd
names = pd.Series(["Grace Brewster Murray Hopper", "Alan Turing"], dtype="string")
print(names.str.rsplit(" ", n=1, expand=True))Here column 0 holds everything before the last space and column 1 holds the final word. split with n=1 would instead cut at the first space.
Ragged results
When rows have different numbers of pieces, expand=True pads the short rows with missing values. The frame is as wide as the longest row.
import pandas as pd
s = pd.Series(["a-b-c", "d-e", None], dtype="string")
print(s.str.split("-", expand=True)) 0 1 2
0 a b c
1 d e <NA>
2 <NA> <NA> <NA>The width depends on the data, which is a hazard. If a batch happens to contain no three-piece rows, you get two columns, and a later assignment to three names raises ValueError. To get a stable shape, fix the column count yourself and then attach the result with join:
import pandas as pd
df = pd.DataFrame({"path": ["a/b/c", "d/e", None]}, dtype="string")
parts = (
df["path"]
.str.split("/", expand=True)
.reindex(columns=range(3), fill_value=pd.NA)
.astype("string")
)
parts.columns = ["top", "mid", "leaf"]
print(df.join(parts))reindex adds any missing columns and drops extra ones. If you cannot afford to drop data, check parts.shape[1] first. The final astype("string") is needed because a column added by reindex is created with object dtype.
A fixed three-way cut with partition
str.partition splits at the first occurrence of a separator and always returns exactly three columns: the text before, the separator, and the text after. The shape never varies, so no padding step is needed.
import pandas as pd
emails = pd.Series(["[email protected]", "no-at-sign", None], dtype="string")
print(emails.str.partition("@"))There is one gotcha. When the separator is absent, partition returns the whole string in the first column and empty strings in the others, not <NA>. Only a truly missing input gives <NA> in all three columns. A later test such as isna() will therefore not catch rows that lacked the separator. Test for == "" instead. rpartition does the same from the right.
Picking pieces without expanding
Sometimes you want one piece and not a whole frame. The .str accessor can index into the lists that split produces:
import pandas as pd
s = pd.Series(["2026-12-01", "2027-01-15"], dtype="string")
year = s.str.split("-").str[0]
last = s.str.split("-").str.get(-1)
print(year.tolist(), last.tolist()).str[0] and .str.get(0) are equivalent. An out-of-range index gives a missing value and does not raise an error. The intermediate Series of lists has dtype object, so the piece you pick may come back as object too. If it matters, finish with .astype("string").
Extracting with regular expressions
Use str.extract when the pieces are defined by a pattern rather than a separator. Each capture group in the regex becomes one output column. Only the first match in each string is used.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
print(s.str.extract(r"id-(\d+)", expand=False))0 001
1 042
2 <NA>
dtype: stringThe row "unknown" does not match, so it gets <NA>. Nothing is raised. That makes extract convenient for messy data, but it also means failures are silent. After extracting, count the rows that came back missing even though the input was present:
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown", None], dtype="string")
ids = s.str.extract(r"id-(\d+)", expand=False)
unmatched = s.notna() & ids.isna()
print(s[unmatched].tolist())This prints ['unknown']. The missing input is not flagged, because it was already missing.
Return shape and the expand argument
The expand argument decides the return type, and it only matters when the pattern has one group.
| Groups in pattern | `expand=True` (default) | `expand=False` |
|---|---|---|
| One | DataFrame with one column | Series |
| Two or more | DataFrame | DataFrame |
| None | `ValueError` | `ValueError` |
A pattern with no capture group raises ValueError, because there is nothing to put in a column. If you only need to test for a match, use str.contains.
Named groups become column names
A named group (?P<name>...) gives the output column that name, so no renaming step is needed.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
parts = s.str.extract(r"(?P<kind>[a-z]+)-(?P<num>\d+)")
print(parts)
print(parts["num"].astype("Int64").tolist()) kind num
0 id 001
1 id 042
2 <NA> <NA>
[1, 42, <NA>]Extracted digits are still text, and leading zeros survive. Converting with astype("Int64") gives a nullable integer column in which the missing row stays <NA>. A plain int64 column cannot hold a missing value.
Use (?:...) for groups you need only for alternation or repetition. A non-capturing group does not create a column. This matters because every (...) in the pattern adds one.
Every match with extractall
str.extractall returns all matches, not just the first. Each match becomes a row, and the index gains a second level named match.
import pandas as pd
s = pd.Series(["a1b22", "c333", None], dtype="string")
found = s.str.extractall(r"(\d+)")
print(found)
print(found.groupby(level=0).size())The first string yields two rows, with index (0, 0) holding 1 and (0, 1) holding 22. The second yields one row. The missing entry and any string with no match produce no rows at all, so the result can be shorter than the input. To bring a result back to the original shape, group on level=0 and use reindex with the original index.
Literal versus regex matching
The splitting and extracting methods differ in how they read the separator you pass.
str.extractandstr.extractallalways treat the pattern as a regex.str.replacetreats the pattern as a literal by default in pandas 2.0 and later, but older versions defaulted to regex. Stateregex=explicitly so the code means the same everywhere.str.splitandstr.rsplittakeregex=Noneby default. A single-character pattern is then literal, and a longer one is read as a regex.
The default in split causes real bugs. A pattern of "." is literal under the default, but ".." is a regex that matches any two characters. Versions with dots in them show the problem:
import pandas as pd
v = pd.Series(["1.2.10", "1.3"], dtype="string")
print(v.str.split(".", expand=True))
print(v.str.split(".", expand=True, regex=False).shape)Both calls work, since a single dot is literal. If you switch to a multi-character separator such as "::", only regex=False keeps it literal if it contains regex symbols such as | or +. To split on a regex deliberately, pass regex=True:
import pandas as pd
s = pd.Series(["a, b;c", "d ;e"], dtype="string")
print(s.str.split(r"\s*[,;]\s*", regex=True, expand=True))Prefer regex=False whenever the separator is a plain string. It is faster, and it cannot be broken by a special character in the data or the pattern.
Choosing a method
The diagram below summarizes the decision. The fixed-versus-variable question matters most, because a variable piece count is what breaks column assignment.
| Method | Returns | Rows with no match or separator |
|---|---|---|
| `split(expand=True)` | DataFrame of varying width | Padded with `<NA>` |
| `partition` | DataFrame, always 3 columns | Whole string, then empty strings |
| `extract` | Series or DataFrame, one column per group | `<NA>` in every column |
| `extractall` | DataFrame, one row per match | No rows |
Pitfalls specific to splitting and extracting
- Missing values pass through. A
<NA>input gives<NA>in every output column ofsplit,partition, andextract. Onobjectcolumns the output may containNaNorNoneinstead, so check dtypes before you compare. - Whitespace stays in the pieces.
"a, b".split(",")gives" b"with a leading space. Follow with.str.strip(), or put the whitespace in a regex separator as shown above. - Column count drift. Do not assign to a fixed list of names unless the width is fixed by
n, bypartition, or byreindex. - Silent non-matches.
extractnever raises on a row that fails to match. Count the unmatched rows as shown earlier. - Types after extraction. Extracted digits are text. Convert with
astype("Int64")orpd.to_numericbefore sorting, or"100"will sort before"20".
Exercise
A string column codes holds values like "NY-2026-0042", "LA-2025-7", and None. Write code that creates three columns, region, year, and serial, using str.extract. Make year and serial nullable integers. What do the None row and a malformed row such as "bad" get?
Show answer
Use named groups and then convert the numeric columns. import pandas as pd codes = pd.Series(["NY-2026-0042", "LA-2025-7", None, "bad"], dtype="string") parts = codes.str.extract(r"(?P<region>[A-Z]{2})-(?P<year>\d{4})-(?P<serial>\d+)") parts["year"] = parts["year"].astype("Int64") parts["serial"] = parts["serial"].astype("Int64") print(parts) The None row and the "bad" row both get <NA> in all three columns, because extract does not raise on a failed match. To tell them apart, compare codes.notna() with parts["region"].isna(). That mask is True only for "bad".
Exercise
The column full holds "Grace Brewster Murray Hopper" and "Alan Turing". You call full.str.split(" ", n=1, expand=True) and get a last name of "Brewster Murray Hopper" for the first row. Which call gives "Hopper" instead, and what does the first column contain then?
Show answer
Use str.rsplit, which counts the cut from the right: full.str.rsplit(" ", n=1, expand=True). Column 1 holds "Hopper" and "Turing". Column 0 holds "Grace Brewster Murray" and "Alan", which is everything before the last space.