In PySpark, splitting a string column into multiple columns or rows is a common transformation when cleaning or reshaping data. The main tools are split() (from pyspark.sql.functions) and regexp_extract() for more complex patterns. This guide walks you through the exact steps, including handling delimiters, multiple splits, and turning split results into new rows.
What You’ll Need
- A working PySpark environment (Databricks, Spark standalone, or local with
pysparkinstalled). - A Spark DataFrame with at least one string column you want to split.
- Basic familiarity with PySpark DataFrame operations (e.g.,
select(),withColumn()).
Step-by-Step
- Import the required functions. At the top of your script, add:
from pyspark.sql.functions import split, col, explode, regexp_extract - Create or load your DataFrame. For testing, you can create a simple one:
df = spark.createDataFrame([("1,2,3",), ("4,5",)], ["nums"]) - Split the string into an array column. Use
split()with the column and delimiter. Example:
df_split = df.withColumn("nums_array", split(col("nums"), ","))
This creates a new columnnums_arraycontaining an array of strings. - Access individual elements of the array. Use the
getItem()method or index notation. For the first element:
df_first = df_split.withColumn("first_num", col("nums_array").getItem(0))
Or with index:col("nums_array")[0]. - Split into multiple columns at once. If you know the number of parts, you can extract them in a single
select():
df.select(col("nums"), split(col("nums"), ",").getItem(0).alias("num1"), split(col("nums"), ",").getItem(1).alias("num2"))
This works but repeats the split; for efficiency, create the array column first, then extract. - Split into rows (explode). If you want each element as a separate row, use
explode():
df_exploded = df.withColumn("num", explode(split(col("nums"), ",")))
This duplicates the original row for each element. - Handle multiple delimiters or regex patterns.
split()accepts a regex. For example, to split on commas or semicolons:
split(col("nums"), "[,;]") - Split with a limit. The second parameter of
split()is a limit. If you set it to 2, the split stops after 2 elements, keeping the rest in the second element:
split(col("nums"), ",", 2) - Trim whitespace after splitting. Often you want to remove spaces around elements. Use
trim()on each element, but note thattrim()works on a column, not an array. So you need to transform the array:
from pyspark.sql.functions import transform
df_trimmed = df.withColumn("nums_array_clean", transform(split(col("nums"), ","), lambda x: trim(x))) - Split and cast to numeric type. If the elements are numbers, cast them after splitting. For example, to create an array of integers:
df.withColumn("nums_int", split(col("nums"), ",").cast("array"))
Or usetransformto cast each element:transform(split(...), lambda x: x.cast("int")).
Common Mistakes
- Forgetting to import
splitorcol. This causes a NameError. Always include the import line. - Using a plain string delimiter that contains regex special characters. For example, splitting on a period (
.) will match any character unless you escape it:split(col("s"), "\\."). - Assuming
split()modifies the original column. It returns a new column; you must assign it withwithColumn()or use it inselect(). - Using
getItem()on a column that is not an array. This throws an error. Ensure the column is an array type first. - Expecting
explode()to keep the original row count. It increases rows; if you need to keep the original rows, usesplit()andgetItem()instead.
Tips
- Use
split()with a limit when you only need the first few parts. This can improve performance if the string is long. - For complex parsing, consider
regexp_extract()instead of splitting. It extracts a specific pattern rather than splitting on a delimiter. - When splitting into multiple columns, create the array once and reuse it to avoid repeated computation. For example:
df.withColumn("arr", split(...)).select(col("arr").getItem(0).alias("a"), col("arr").getItem(1).alias("b")) - If you need to split into a fixed number of columns of different types, cast each element individually after extraction.
- Test with a small sample before running on large data. Use
df.limit(10)to verify the logic.
Troubleshooting
- Error: “Column not iterable” or “Cannot resolve column” — Make sure you are passing a column object, not a string, to
split(). Usecol("column_name"). - Error: “TypeError: ‘Column’ object is not callable” — You might be using parentheses incorrectly. For example,
col("nums")[0]is correct, butcol("nums")(0)is not. - Split result contains empty strings. If your delimiter appears at the start or end, or there are consecutive delimiters, you get empty strings. Use
filterorarray_removeto clean them. - Performance is slow on large DataFrames. Avoid multiple
split()calls on the same column. Compute the array once and reuse it. - Regex delimiter not working as expected. Remember that
split()uses Java regex. Test your regex in a simple Spark expression first.
Frequently Asked Questions
- Q: Can I split a string into multiple columns without knowing the number of parts?
A: No, you need to know the maximum number of parts to create a fixed number of columns. If the number varies, consider usingexplode()to get rows instead. - Q: How do I split on multiple different delimiters?
A: Use a regex character class, e.g.,split(col("s"), "[,;]")splits on comma or semicolon. - Q: What is the difference between
split()andregexp_extract()?
A:split()breaks the string into an array of substrings based on a delimiter.regexp_extract()pulls out a specific substring that matches a pattern. Usesplit()when you want all parts; useregexp_extract()when you want only certain parts. - Q: How do I split a string and convert the parts to integers?
A: After splitting, cast the array toarrayusing.cast("array, or transform each element with") lambda x: x.cast("int"). - Q: Can I split a string column in place without creating a new column?
A: No, DataFrame transformations are immutable. You must assign the result to a new DataFrame or overwrite the original variable. - Q: Why does
explode()increase the number of rows?
A:explode()generates one row per element in the array. If the array has 3 elements, the original row becomes 3 rows. This is useful for normalization.
Related
- What Is a Stop Charge? Meaning, Fees & How It Works
- Updates as a Noun: Meaning, Usage & Examples
- Cali Highway 4 Sign: What It Means & Where
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Indent Text in an Excel CellTo indent content in an Excel cell, select the cell or cells, then choose Home > Alignment >…
- How to Unmerge Cells in Excel and Keep DataTo unmerge cells in Excel for Microsoft 365 on Windows, select the merged cell or range, then choose…
- How to Delete a Landscape Page in Microsoft Word EasilyTo delete a landscape page in Word, remove the page’s content and then check its section breaks; Word…
- Excel Power Query: Open It, Import Data, and RefreshIn Excel for Microsoft 365 on Windows, open the Data tab and choose Get Data > Launch Power…
- Excel Two-Variable Data Tables: Setup and ExamplesAn Excel two-variable data table tests how one formula’s result changes across combinations of two input values. In…
- Google Sheets: Count Cells Containing Text?Yes. In Google Sheets, use =COUNTIF(A2:A100,"*") to count cells containing text in the range A2:A100. If you want…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.