How to Split a String in PySpark (with Examples)

How-to basics · Updated November 22, 2026

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 pyspark installed).
  • 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

  1. Import the required functions. At the top of your script, add:
    from pyspark.sql.functions import split, col, explode, regexp_extract
  2. Create or load your DataFrame. For testing, you can create a simple one:
    df = spark.createDataFrame([("1,2,3",), ("4,5",)], ["nums"])
  3. 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 column nums_array containing an array of strings.
  4. 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].
  5. 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.
  6. 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.
  7. Handle multiple delimiters or regex patterns. split() accepts a regex. For example, to split on commas or semicolons:
    split(col("nums"), "[,;]")
  8. 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)
  9. Trim whitespace after splitting. Often you want to remove spaces around elements. Use trim() on each element, but note that trim() 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)))
  10. 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 use transform to cast each element: transform(split(...), lambda x: x.cast("int")).

Common Mistakes

  • Forgetting to import split or col. 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 with withColumn() or use it in select().
  • 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, use split() and getItem() 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(). Use col("column_name").
  • Error: “TypeError: ‘Column’ object is not callable” — You might be using parentheses incorrectly. For example, col("nums")[0] is correct, but col("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 filter or array_remove to 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 using explode() 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() and regexp_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. Use split() when you want all parts; use regexp_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 to array using .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

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.