Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Pandas Split Function: How to Split Strings in a Column

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The pandas split function is actually the .str.split() accessor: it splits each string in a Series on a delimiter and returns either a list per row or, with expand=True, a new DataFrame of separate columns. You need pandas installed and a DataFrame with at least one string column; then call df['col'].str.split(',', expand=True) and assign the result to new columns. The steps below cover the exact syntax, how to keep the original column, how to limit the number of splits, and what to do when NaNs or mixed types break the call.

What You'll Need

  • A working Python environment (Python 3.8 or newer is a safe baseline) with pandas installed. Run pip install pandas if import pandas fails.
  • A DataFrame or Series whose values are strings. If the column is numeric or contains mixed types, convert it first with .astype(str) or clean it before splitting.
  • A delimiter that actually appears in the data: a comma, semicolon, pipe, space, hyphen, or a regular expression if you use pat=.

Step-by-Step

  1. Import pandas and create or load your data. For example: import pandas as pd then df = pd.DataFrame({'full_name': ['Ada Lovelace', 'Alan Turing', 'Grace Hopper']}). The column must hold strings; if it holds numbers, run df['full_name'] = df['full_name'].astype(str) first.
  2. Select the string column and use the .str accessor. The syntax is df['full_name'].str.split(' '). This returns a Series where each row is a Python list, for example ['Ada', 'Lovelace']. It does not modify the original DataFrame.
  3. Add expand=True to get separate columns. Use df['full_name'].str.split(' ', expand=True). The result is a DataFrame with one column per split position, numbered 0, 1, 2 and so on. Rows with fewer parts get None in the extra columns.
  4. Assign the result to new columns. Either assign the whole frame with df[['first', 'last']] = df['full_name'].str.split(' ', expand=True), or assign one column at a time with df['first'] = df['full_name'].str.split(' ').str[0]. The second form is useful when you only need the first token.
  5. Limit the number of splits with n. df['col'].str.split(',', n=1, expand=True) splits only on the first comma, so the remainder stays together in the second column. This is the correct approach for values like "city, state, country" when you want city and the rest.
  6. Use a regular expression when the delimiter varies. Pass pat= and regex=True: df['col'].str.split(pat=r'[,;|]', regex=True, expand=True). This splits on a comma, semicolon or pipe in one call. Without regex=True, a multi-character pattern is treated as a literal string.
  7. Drop or keep the original column deliberately. After assigning new columns, run df = df.drop(columns=['full_name']) if you no longer need it. If you want to keep it, do nothing; the split result is a copy, so the original stays intact until you overwrite it.
  8. Check the output before moving on. Run print(df.head()) and print(df.dtypes). Split columns are object dtype even when they contain numbers, so convert with pd.to_numeric(df['price'], errors='coerce') if you need arithmetic.

Common Mistakes

  • Forgetting .str. Calling df['col'].split(',') raises an AttributeError because a Series has no split method. The string accessor is required.
  • Assuming expand=True pads with empty strings. It pads with None, which becomes NaN in numeric contexts. Decide whether to fill those with .fillna('') or leave them.
  • Splitting on a delimiter that also appears inside quoted values. A naive comma split breaks CSV-like text such as "Smith, John". Use Python's csv module or a regex that respects quotes; .str.split() does not parse quoting rules.
  • Ignoring NaN rows. By default, NaN values stay NaN and do not raise. If you expected a split, check for missing data with df['col'].isna().sum() first.
  • Using n and expand in the wrong order. The signature is split(pat=None, n=-1, expand=False, regex=None). Keyword arguments avoid confusion; positional arguments are easy to mix up.
  • Expecting the original column to change. .str.split() returns a new object. You must assign it back or to new columns.

Tips

  • Use rsplit when you want to split from the right, for example to separate a file extension: df['path'].str.rsplit('.', n=1, expand=True).
  • Name the resulting columns immediately: split_df.columns = ['first', 'last']. This is clearer than leaving 0, 1, 2.
  • For a single token, .str.split(' ').str[0] is concise, but .str.extract(r'^(\S+)') is often faster on large data.
  • Trim whitespace before splitting: df['col'] = df['col'].str.strip(). Otherwise "a, b" yields ' b' with a leading space.
  • When the number of parts varies, use expand=True and then rename or select only the columns you need rather than assuming a fixed count.

Troubleshooting

  • AttributeError: Can only use .str accessor with string values. The column contains numbers, dates or mixed types. Convert with .astype(str), or select only string rows first.
  • ValueError: cannot set a frame with no defined index. This usually means the split returned an empty result or the assignment shape does not match. Check that the column name exists and that expand=True is set when assigning multiple columns.
  • All values land in one column. The delimiter probably does not match the data. Print a few raw values with df['col'].head().tolist() and confirm the exact character, including spaces.
  • Unexpected NaN in new columns. Rows had fewer parts than the maximum, or the original value was missing. Fill with .fillna('') or investigate the source rows.
  • Regex pattern splits too much. Escape special characters or use a character class such as [,;]. Test the pattern on a small Series before applying it to the full DataFrame.

Frequently Asked Questions

What does str.split() return in pandas?

It returns a Series of lists by default. With expand=True it returns a DataFrame with one column per split position.

How do I split a column into multiple columns?

Use df['col'].str.split(delimiter, expand=True) and assign the result to new column names, for example df[['a','b']] = ....

Can I split on multiple delimiters at once?

Yes, by passing a regular expression with regex=True, such as pat=r'[,;|]'. Without regex mode, the pattern is treated literally.

How do I keep only the first part after splitting?

Use df['col'].str.split(delim).str[0], or .str.split(delim, n=1, expand=True)[0].

Why do I get NaN after splitting?

Rows with fewer delimiters than the widest row are padded with None/NaN, and original missing values remain missing. Fill or filter as needed.

Does str.split() modify the original DataFrame?

No. It returns a new Series or DataFrame. You must assign the result back to a column or to new columns.