CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 3 · Lesson 12/33

    Reshaping DataFrames: withColumn, drop, split, filter and explode

    Manipulate columns, rows, and table structures by adding, dropping, splitting, renaming column names, applying filters, and exploding arrays

    18 min read
    3.14% of exam
    15 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Add or replace columns with withColumn and withColumns, and reassign the result
    • Rename columns with withColumnRenamed and remove them with drop, knowing when each silently does nothing
    • Split a delimited string into an array with split, or pull out one piece with split_part
    • Filter rows with a Column expression or a SQL string using filter or where
    • Choose between explode, explode_outer and inline for arrays, maps and arrays of structs

    Key concept

    Transformations return a new DataFrame — withColumn, withColumnRenamed, drop and filter never change the DataFrame you call them on. Each one returns a new DataFrame, so you have to assign that result to a variable before later steps can use it.

    1.Adding and replacing columns with withColumn

    Turning bronze data into something analysts can use mostly means reshaping it. You derive a total from a price and a quantity, give a column a consistent name, remove an internal field, keep only the rows that matter, and flatten a nested array into rows. In PySpark each of these is a DataFrame method, and each one returns a new DataFrame. The original stays unchanged. A notebook that adds a column and then keeps working with it therefore reassigns the result: orders_df = orders_df.withColumn("total", col("price") * col("quantity")).

    withColumn(colName, col) takes two arguments: a string naming the column and a Column expression that computes its value. If a column with that name already exists, its values are replaced. Otherwise the column is added at the end. The same method therefore covers both deriving a new field and overwriting an existing one in place, for example recomputing age from a corrected source.

    withColumn adds age2 computed from an existing column; the original columns are keptpython
    df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
    df.withColumn('age2', df.age + 2).show()
    # +---+-----+----+
    # |age| name|age2|
    # +---+-----+----+
    # |  2|Alice|   4|
    # |  5|  Bob|   7|
    # +---+-----+----+

    Two lookalikes do something different. select projects only the expressions you list, so the result loses every column you leave out. A string such as "price * quantity" is a SQL expression, and selectExpr is the method that projects SQL expressions. When you want to keep the full row and add one computed field, withColumn with a Column expression is the direct tool.

    Calling withColumn many times is a performance hazard. Each call adds a projection to the query plan, so a loop that adds twenty columns one by one builds a large plan. That can slow planning and can even throw a StackOverflowException. withColumns solves this. It takes one dictionary that maps column names to Column expressions and applies every addition or replacement in a single call. Only one map is accepted per call. A select that lists all the columns at once avoids the problem too.

    withColumns adds two derived columns in one call from a dictpython
    df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
    df.withColumns({'age2': df.age + 2, 'age3': df.age + 3}).show()
    # +---+-----+----+----+
    # |age| name|age2|age3|
    # +---+-----+----+----+
    # |  2|Alice|   4|   5|
    # |  5|  Bob|   7|   8|
    # +---+-----+----+----+

    Checkpoint 1 of 9· Fill the gap

    The output keeps every original column and adds age2. Which method completes this sample?

    df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
    df. ? ('age2', df.age + 2).show()
    # +---+-----+----+
    # |age| name|age2|
    # +---+-----+----+
    # |  2|Alice|   4|
    # |  5|  Bob|   7|
    # +---+-----+----+

    Checkpoint 2 of 9· Check yourself

    A notebook adds twenty derived columns by calling withColumn once per column inside a for loop. Planning has become slow, and one run threw a StackOverflowException. What is the recommended fix?

    Checkpoint 3 of 9· Exam question

    A data engineer is working with a Spark DataFrame orders_df that has columns price and quantity. They need to add a new column total equal to price multiplied by quantity, then reassign the result to orders_df for later steps in the same notebook. Which line of code correctly does this?

    Checkpoint 4 of 9· Exam question

    Which statement accurately distinguishes the DataFrame withColumns method from chaining several separate withColumn calls?

    Sources123

    2.Renaming and dropping columns

    withColumnRenamed(existing, new) takes exactly two strings, the current name and the new one. It does not take a third argument and does not compute anything. To rename several columns, pass a dict of old-to-new names to withColumnsRenamed. To replace every column name at once, toDF(*cols) returns a new DataFrame with the names you list.

    A rename that matches nothing does not fail. If the schema has no column with the existing name, withColumnRenamed returns the DataFrame unchanged. A typo such as "custmer_id" therefore passes silently, and the mistake shows up later as a missing column downstream. withColumnsRenamed behaves the same way for each name in its dict.

    drop(*cols) returns a new DataFrame without the named columns. All other columns keep their names, types and values. Dropping a column that doesn't exist does nothing, just like a mismatched rename. Arguments can be names or Column objects, and the two aren't equivalent. A name is matched literally, while a Column is matched as an expression, which matters after a join when both inputs have a column with the same name.

    Dropping by name after a join removes the shared name column, leaving age and heightpython
    df2 = spark.createDataFrame([(80, "Tom"), (85, "Bob")], ["height", "name"])
    df.join(df2, df.name == df2.name).drop('name').sort('age').show()
    # +---+------+
    # |age|height|
    # +---+------+
    # | 14|    80|
    # | 16|    85|
    # +---+------+

    Say a silver notebook must keep a free-text internal_notes column out of gold tables. customers_df.drop("internal_notes") is the only one of the usual candidates that removes the column. A filter on that column changes which rows survive, but the schema keeps the column. withColumn("internal_notes", ...) replaces its values and the column stays. dropDuplicates removes duplicate rows (deduplication) and leaves every column in place.

    Which method changes what
    MethodChangesIf the named column is missing
    withColumn / withColumnsAdds a column, or replaces the values of one with the same nameAdds it as a new column
    withColumnRenamed / withColumnsRenamedColumn names onlyNo-op: DataFrame returned unchanged
    dropRemoves columns; others untouchedNo-op: DataFrame returned unchanged
    filter / whereWhich rows are kept; schema unchangedNot applicable

    Checkpoint 5 of 9· Check yourself

    In a silver notebook, orders_df = orders_df.withColumnRenamed("cust_id", "customer_key") runs on a DataFrame whose column is actually named customer_id. What does this line do?

    Checkpoint 6 of 9· Exam question

    A silver-layer notebook reads a DataFrame customers_df that includes an internal_notes column containing free-text data the downstream gold tables must never expose. The engineer needs to remove this column before writing the output, while keeping every other column unchanged. Which approach correctly does this?

    Sources4536

    3.Splitting a string column into parts

    Delimited strings such as "apple,banana,cherry" or "2024-03-15" often hold several values in one field. split(str, pattern, limit) from pyspark.sql.functions turns that string into an array of strings. The pattern is a Java regular expression, not a plain delimiter. That means '[ABC]' splits on any of A, B or C, and characters such as . or | need escaping before they act as literal delimiters.

    limit controls how many times the pattern is applied. If limit is greater than 0, the array has at most limit elements and the last element holds everything after the final match. If limit is 0 or less (0 is the default), the pattern is applied as many times as possible. A delimiter at the very end of the string produces a trailing empty element. That surprise usually shows up as an extra blank value once the array is exploded.

    limit 2 keeps the remainder in the last element; -1 splits fully, including a trailing empty stringsql
    > SELECT split('oneAtwoBthreeC', '[ABC]', 2);
     [one,twoBthreeC]
    
    > SELECT split('oneAtwoBthreeC', '[ABC]', -1);
     [one,two,three,]

    When you need just one piece as a column, for example the year from "2024-03-15", use split_part(src, delimiter, partNum). It returns that single part directly. partNum is 1-based, and negative values count back from the end. A part number past the last piece returns an empty string, and partNum 0 raises an error. Unlike split, split_part takes a plain delimiter rather than a regular expression. You can feed the results into withColumns to fan one string out into several named columns. Alternatively, keep the array from split and explode it into rows, as shown below.

    Checkpoint 7 of 9· Check yourself

    A silver notebook runs tagged_df = raw_df.withColumn("tags", split(col("tags"), ",")). In raw_df, tags is a comma-delimited string column. Which statement about the two DataFrames is correct?

    Sources789

    4.Filtering rows with filter and where

    filter(condition) keeps the rows where the condition is true. where is an alias with identical behaviour, so choosing between them is a matter of style. The condition can be a Column of BooleanType, such as df.age > 3 or col("status") == "active", or a SQL expression string such as "age > 3". The string form is convenient when the predicate comes from configuration. The Column form fails at the line that builds it if a referenced attribute doesn't exist, which makes typos easier to find.

    Compound conditions combine Column expressions with & (and) and | (or). Wrap each comparison in its own parentheses, because Python's operator precedence would otherwise bind & before > and ==. In a SQL string you write AND and OR as you would in a WHERE clause.

    Two Column conditions combined with &, each in parenthesespython
    df.filter((df.age > 3) & (df.subject == "Physics")).show()
    # +---+----+-------+
    # |age|name|subject|
    # +---+----+-------+
    # |  5| Bob|Physics|
    # +---+----+-------+

    A filter changes how many rows you have. It never changes the schema: every column of the input is still there in the output, including the column you filtered on.

    Checkpoint 8 of 9· Fill the gap

    The input DataFrame has three rows: (2, Alice, Math), (5, Bob, Physics) and (7, Charlie, Chemistry). Only Bob's row survives the filter. Which operator joins the two Column conditions?

    df.filter((df.age > 3)  ?  (df.subject == "Physics")).show()
    # +---+----+-------+
    # |age|name|subject|
    # +---+----+-------+
    # |  5| Bob|Physics|
    # +---+----+-------+

    Sources103

    5.Exploding arrays and maps into rows

    Nested data from JSON or APIs often arrives with an array per record: line items per order, tags per article. explode turns each element into its own row and copies the other columns of the parent row onto every new row. For a map, each key/value pair becomes a row. The output column is named col for array elements, and key and value for maps, unless you rename it with .alias(). For more on landing that data, see semi-structured ingestion.

    explode: four rows for i=1, none for the empty (i=2) or NULL (i=3) arrayspython
    df.select('*', sf.explode('a')).show()
    
    +---+---------------+----+
    |  i|              a| col|
    +---+---------------+----+
    |  1|[1, 2, 3, NULL]|   1|
    |  1|[1, 2, 3, NULL]|   2|
    |  1|[1, 2, 3, NULL]|   3|
    |  1|[1, 2, 3, NULL]|NULL|
    +---+---------------+----+

    Silently losing those parent rows is a common bug. For example, an order with no line items vanishes from a silver table and a row count stops reconciling. explode_outer fixes this. When the array or map is NULL or empty, it emits one row with NULL in the exploded column, so every parent row survives. Use explode when a record without elements has no meaning downstream. Use explode_outer when every parent must still appear.

    explode_outer on the same data keeps i=2 and i=3 with col = NULLpython
    df = spark.sql('SELECT * FROM VALUES (1,ARRAY(1,2,3,NULL)), (2,ARRAY()), (3,NULL) AS t(i,a)')
    df.select('*', sf.explode_outer('a')).show()
    
    +---+---------------+----+
    |  i|              a| col|
    +---+---------------+----+
    |  1|[1, 2, 3, NULL]|   1|
    |  1|[1, 2, 3, NULL]|   2|
    |  1|[1, 2, 3, NULL]|   3|
    |  1|[1, 2, 3, NULL]|NULL|
    |  2|             []|NULL|
    |  3|           NULL|NULL|
    +---+---------------+----+

    Arrays of structs need one more step. Exploding them gives one struct per row. To turn the struct fields into top-level columns, alias the exploded column and select alias.*. inline does both steps in one call, producing one column per struct field, and inline_outer is its variant that keeps NULL or empty arrays. Only one explode is allowed per select. To explode two arrays, chain two selects. The result is every combination of their elements, so row counts multiply.

    Explode an array of structs, then flatten the struct with s.*python
    import pyspark.sql.functions as sf
    df = spark.sql('SELECT ARRAY(NAMED_STRUCT("a",1,"b",2), NAMED_STRUCT("a",3,"b",4)) AS a')
    df.select(sf.explode('a').alias("s")).select("s.*").show()
    
    +---+---+
    |  a|  b|
    +---+---+
    |  1|  2|
    |  3|  4|
    +---+---+

    SQL has the same generators. From Databricks Runtime 12.2 LTS, call them as table references in FROM, naming the output columns in the alias. Calling them in the SELECT list or a LATERAL VIEW is deprecated.

    SQL table-reference form: name the exploded columns in the aliassql
    > SELECT elem, 'Spark' FROM explode(array(10, 20)) AS t(elem);
     10 Spark
     20 Spark
    
    > SELECT num, val, 'Spark' FROM explode(map(1, 'a', 2, 'b')) AS t(num, val);
     1   a   Spark
     2   b   Spark

    Checkpoint 9 of 9· Fill the gap

    Input row 2 has a NULL array, yet the output still has a row for it, with NULL in elem. Which generator goes in the blank?

    > SELECT  ? (c1) AS elem, 'Spark' FROM VALUES(array(10, 20)), (null) AS T(c1);
     10   Spark
     20   Spark
     NULL Spark

    Sources1112131415

    Sources

    (15)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Returns a new DataFrame by adding a column or replacing the existing column that has the same name.”
      ↩︎ Adding and replacing columns with withColumn
      “To avoid this, use select with multiple columns at once.”
      ↩︎ Adding and replacing columns with withColumn
      “Returns a new DataFrame by adding a column or replacing the existing column that has the same name.”
      ↩︎ Key concept
      “calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans”
      ↩︎ Exam trap 1
      “calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans which can cause performance issues”
      ↩︎ Checkpoint
      “Returns a new DataFrame by adding a column or replacing the existing column that has the same name.”
      ↩︎ Checkpoint
    2. 2.
      “Returns a new DataFrame by adding multiple columns or replacing the existing columns that have the same names.”
      ↩︎ Adding and replacing columns with withColumn
      “a dict of column name and Column. Currently, only a single map is supported.”
      ↩︎ Adding and replacing columns with withColumn
    3. 3.
      “Projects a set of SQL expressions and returns a new DataFrame.”
      ↩︎ Adding and replacing columns with withColumn
      “Returns a new DataFrame with new specified column names.”
      ↩︎ Renaming and dropping columns
    4. 4.
      “Returns a new DataFrame by renaming an existing column. This is a no-op if the schema doesn't contain the given column name.”
      ↩︎ Renaming and dropping columns
      “Returns a new DataFrame by renaming an existing column. This is a no-op if the schema doesn't contain the given column name.”
      ↩︎ Exam trap 2
      “This is a no-op if the schema doesn't contain the given column name.”
      ↩︎ Checkpoint
    5. 5.
      “A dict of existing column names and corresponding desired column names.”
      ↩︎ Renaming and dropping columns
    6. 6.
      “Returns a new DataFrame without specified columns. This is a no-op if the schema doesn't contain the given column name(s).”
      ↩︎ Renaming and dropping columns
      “So dropping a column by its name drop(colName) has a different semantic with directly dropping the column drop(col(colName)).”
      ↩︎ Renaming and dropping columns
    7. 8.
      “the resulting array's last entry will contain all input beyond the last matched regex.”
      ↩︎ Splitting a string column into parts
      “The trailing empty element comes from the delimiter at the end of the string.”
      ↩︎ Splitting a string column into parts
    8. 9.
      “if partNum is out of range of split parts, returns empty string.”
      ↩︎ Splitting a string column into parts
    9. 10.
      “A Column of BooleanType or a string of SQL expressions.”
      ↩︎ Filtering rows with filter and where
      “A new DataFrame with rows that satisfy the condition.”
      ↩︎ Filtering rows with filter and where
    10. 11.
      “Uses the default column name col for elements in the array and key and value for elements in the map unless specified otherwise.”
      ↩︎ Exploding arrays and maps into rows
      “Only one explode is allowed per SELECT clause.”
      ↩︎ Exploding arrays and maps into rows
    11. 12.
      “Unlike explode, if the array/map is null or empty then null is produced.”
      ↩︎ Exploding arrays and maps into rows
      “Unlike explode, if the array/map is null or empty then null is produced.”
      ↩︎ Exam trap 3
    12. 14.
      “If input is NULL a single row with NULLs for each column is produced.”
      ↩︎ Exploding arrays and maps into rows
    13. 15.
      “Invocation from the LATERAL VIEW clause or the SELECT list is deprecated. Instead, invoke explode as a table_reference.”
      ↩︎ Exploding arrays and maps into rows
      “If collection is NULL no rows are produced.”
      ↩︎ Prediction

    Continue to part 2 of 2

    Changing Delta table columns with ALTER TABLE

    Spotted a mistake, or was something unclear? Tell us.