str.split
df["col"].str.split("-", expand=True) splits each string on the separator and returns one column per piece; without expand it returns a Series of lists. Use n=1 to split only once and str[0] or str[-1] to take a single piece.
Syntax
Series.str.split(pat=None, n=-1, expand=False, regex=None)| Part | What it is |
|---|---|
pat | Separator string or regex; default splits on whitespace |
n | Maximum number of splits; -1 means all |
expand | True returns a DataFrame with one column per piece |
Examples
import pandas as pd
df = pd.DataFrame({"full_name": ["Ana Silva", "Ben Lee", "Cara De Luca"]})
df[["first", "last"]] = df["full_name"].str.split(" ", n=1, expand=True)
dfResult: full_name first last 0 Ana Silva Ana Silva 1 Ben Lee Ben Lee 2 Cara De Luca Cara De Luca
n=1 keeps multi-word last names together.
codes = pd.Series(["US-NY-001", "UK-LN-042"])
codes.str.split("-").str[-1]Result: 0 001 1 042 dtype: object
codes.str.extract(r"-(\d+)$").astype(int)[0].tolist()Result: [1, 42]
str.extract pulls out a regex group; here the trailing digits.
Common mistakes
- ValueError: Columns must be same length as key when assigning to new columns: some rows split into a different number of pieces; use n= to fix the count or check for NaN.
- Splitting on a dot or pipe gives empty pieces: those are regex characters; pass regex=False or escape them.
- A column of lists is hard to use: add expand=True, or use .str[i] to pick a piece.
Practice str.split
These drills check your answer on live data, free, no account needed.
- Pull numbers out of codesEach code looks like ORD-2024-0153. Extract the final group of digits as an integer (so 0153 becomes 153) and return it as a Series.
- Tidy up text with strip and lowerThe emails in `signups` have stray spaces and mixed case. Return the `email` column as a Series with spaces removed from both ends and every letter in lowercase.
Questions
How do I split a column into rows instead of columns?
Split into lists, then df.explode("col") gives one row per element.
How do I split from the right?
Series.str.rsplit("-", n=1, expand=True) splits on the last separator only.
Related
- explodeHow to use explode in pandas to expand a column of lists or comma-separated strings into separate rows, keep other columns, reset the index, and count tags.
- str.containsHow to use str.contains in pandas to find rows containing text: case-insensitive matching, several keywords with regex, literal characters, and the NaN error.
- astypeHow to change a column type in pandas with astype and pd.to_numeric: text to numbers, float to int, strings, categories, nullable Int64, bad values and NaN.
- renameHow to rename columns in pandas with rename(columns={...}), rename every column with a function like str.lower, assign df.columns, and rename the index.