CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 12/32

    Adding, renaming, dropping, filtering, splitting and exploding DataFrame columns

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

    21 min read
    3% of exam
    11 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Add or replace columns with withColumn and withColumns, and say when select fits better
    • Rename columns with withColumnRenamed, withColumnsRenamed and alias, and predict the no-op when a name is missing
    • Drop one or several columns with drop, including after a join
    • Filter rows with filter or where using Column conditions, SQL strings and combined & / | conditions
    • Split a string column into an array with split and its limit argument
    • Turn array elements into rows with explode, and keep empty or null arrays with explode_outer

    Key concept

    Transformations return a new DataFrame — Adding, renaming, dropping and filtering never change the DataFrame you call them on. Each one returns a new DataFrame, so you assign every step to a name and inspect that result.

    1.Adding and replacing columns with withColumn

    Data rarely arrives in the shape the next step needs. A column has the wrong name, a flag is missing, several values are packed into one string, or half the rows are irrelevant. Adding, renaming, dropping, splitting, filtering and exploding are the DataFrame operations that reshape a table into the form the next step expects.

    A DataFrame is never changed in place. Every column operation on this page returns a new DataFrame and leaves the one you called it on as it was. That is why pipelines give each step its own name, such as orders_tiered or df2. Reshaping a table is a chain of small transformations, and each one produces the input for the next.

    withColumn(colName, col) is the usual way to add one column. It takes the new column's name as a string and a Column expression that computes it. It returns every existing column plus the new one. The expression can be arithmetic such as df.age + 2, a comparison such as col("c_acctbal") > 1000 that produces a boolean flag, or a conditional label built from other columns.

    withColumn keeps age and name and appends the computed age2python
    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|
    # +---+-----+----+

    If you reuse an existing name, withColumn replaces that column instead of adding a second one. So one method does two jobs. It adds derived columns, and it overwrites a column with a changed version of itself. A cast such as withColumn("c_custkey", col("c_custkey").cast(StringType())) keeps the name and changes the type.

    withColumns does the same for several columns in one call. It takes a single dict that maps each column name to its Column expression. Names that already exist are replaced and new names are appended. For example, df.withColumns({'age2': df.age + 2, 'age3': df.age + 3}) returns age, name, age2 and age3.

    Each withColumn call adds a projection to the query plan. One or two calls are harmless. A Python loop that calls withColumn once per column is not: fifty calls for fifty features build a deeply nested plan. That plan slows the job down and can end in a StackOverflowException. Pass all the expressions in one call instead, with withColumns or a single select.

    select also produces columns, but it works differently. It projects exactly the expressions you list, so it returns only those columns unless you also list the existing ones. withColumn keeps every column and adds or replaces one name. When you want the same table plus one labelled column, use withColumn. withColumnRenamed and withColumnsRenamed only change names and cannot compute values. filter removes rows and adds no columns.

    DataFrame methods that change the table's columns or rows
    MethodWhat it returns
    withColumn(colName, col)A new DataFrame with one column added, or replaced if the name exists
    withColumns(*colsMap)A new DataFrame with several columns added or replaced
    select(*cols)A new DataFrame projecting only the listed expressions
    withColumnRenamed(existing, new)A new DataFrame with one existing column renamed
    withColumnsRenamed(colsMap)A new DataFrame with several columns renamed
    drop(*cols)A new DataFrame without the specified columns
    filter(condition) / where(condition)A new DataFrame keeping only rows that satisfy the condition

    Checkpoint 1 of 9· Fill the gap

    The output keeps every original column (age, name) and adds a computed age2. Which method completes the call?

    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· Exam question

    An analyst has a DataFrame orders with columns order_id, amount, and region. They need to add a new column amount_tier that labels rows as "high" when amount is greater than 1000 and "standard" otherwise, without mutating the original DataFrame: orders_tiered = orders.____( "amount_tier", when(col("amount") > 1000, "high").otherwise("standard") ) Which method correctly completes this task?

    Sources1234

    2.Renaming columns with withColumnRenamed and alias

    withColumnRenamed(existing, new) renames one column. Most mistakes come from the argument order. The column's current name comes first and the name you want comes second. The two are easy to swap when they look alike, as cust_nm and customer_name do.

    When the source name of a rename is missing, the rename silently does nothing. Spark raises no error, adds no column, and does not match by position. The returned DataFrame has the same columns as the input, so df2.columns still shows cust_nm. The problem only appears later, when a downstream step asks for customer_name and can't find it. If you are unsure about a rename, check df2.columns straight after it.

    Renaming a column that does not exist returns the schema unchangedpython
    df.withColumnRenamed("non_existing", "new_name").show()
    # +---+-----+
    # |age| name|
    # +---+-----+
    # |  2|Alice|
    # |  5|  Bob|
    # +---+-----+

    withColumnsRenamed renames several columns at once. It takes one dict that maps existing names to new names, such as {"age": "age2", "name": "name2"}. Keys that are not in the schema are also a no-op. Chaining withColumnRenamed calls gives the same result, one column at a time.

    alias names an expression at the moment it is created, rather than renaming a column afterwards. Use it when a computed column would otherwise get an awkward generated name, which happens most often with aggregates. avg(df_customer["c_acctbal"]).alias("avg_account_balance") names the result as it is produced. Aggregation itself is covered in aggregate operations on DataFrames. The point here is that alias is called on a Column, while withColumnRenamed is called on a DataFrame.

    Checkpoint 3 of 9· Check yourself

    A pipeline computes avg(df_customer["c_acctbal"]) inside groupBy("c_mktsegment").agg(...). The result column should be called avg_account_balance as soon as it is produced, not under a generated name. Which approach does that?

    Checkpoint 4 of 9· Exam question

    DataFrame df has a column named cust_nm. A developer intends to rename cust_nm to customer_name and runs: df2 = df.withColumnRenamed("customer_name", "cust_nm") What is the result?

    Sources546

    3.Dropping columns with drop

    drop removes columns, and it takes any number of them in one call. df.drop("c_phone", "balance_flag_renamed") returns the remaining columns in their original order. So dropping email and phone from a table with customer_id, email, phone and signup_date leaves ['customer_id', 'signup_date']. The original DataFrame still has all four.

    As with renaming, dropping a name that is not in the schema does nothing and raises no error. That makes drop safe to run when the input sometimes lacks a column. It also means a typo in the name fails silently and the column stays in the output.

    Passing a string to drop is not the same as passing a Column. A string is matched literally, as a column name. A Column object is matched as an expression. The difference matters after a join, when both inputs have a column called name.

    The join example below starts from a df of three people with an age and a name. A second DataFrame, df2, holds a height for two of those names.

    The df used in the join: ages and names for Tom, Alice and Bobpython
    df = spark.createDataFrame(
        [(14, "Tom"), (23, "Alice"), (16, "Bob")], ["age", "name"])
    Dropping by string name after a join removes both same-named columnspython
    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|
    # +---+------+

    Only Tom and Bob appear in both DataFrames, so Alice (23) has no match and is absent from the result. The joined table had two name columns, and drop('name') removed both, leaving age and height. Passing the Column object df2.name instead matches the expression from one input only. Joins themselves are covered in combining DataFrames with joins.

    Checkpoint 5 of 9· Check yourself

    Given a DataFrame df with columns customer_id, email, phone and signup_date, a developer runs df2 = df.drop("emial", "phone"). The first name is misspelled. What is df2.columns?

    Checkpoint 6 of 9· Exam question

    DataFrame customers has columns customer_id, email, phone, and signup_date. A pipeline runs: result = customers.drop("email", "phone") print(result.columns) What is printed?

    Sources74

    4.Filtering rows with filter and where

    filter keeps the rows that meet a condition and drops the rest. where is an alias for filter and behaves exactly the same. Use whichever reads better to your team; SQL users often prefer where. Either way you get the same DataFrame.

    The condition can take two forms. One is a boolean Column, such as df.age > 3 or col("c_custkey") == 412449. The other is a SQL string, such as "age > 3". In the example below, the table holds Alice (2), Bob (5) and Charlie (7). The Column condition and the SQL string both return Bob and Charlie.

    filter and where accept a Column condition or a SQL stringpython
    df.filter(df.age > 3).show()
    # +---+-------+---------+
    # |age|   name|  subject|
    # +---+-------+---------+
    # |  5|    Bob|  Physics|
    # |  7|Charlie|Chemistry|
    # +---+-------+---------+
    
    df.where(df.age == 2).show()
    # +---+-----+-------+
    # |age| name|subject|
    # +---+-----+-------+
    # |  2|Alice|   Math|
    # +---+-----+-------+
    
    df.filter("age > 3").show()

    To combine conditions, use & for AND and | for OR, with each comparison in its own parentheses. df.filter((df.age > 3) & (df.subject == "Physics")) keeps only Bob. df_customer.filter((col("c_nationkey") == 20) & (col("c_acctbal") > 1000)) keeps customers from nation 20 whose balance is over 1000. Always write each comparison in its own parentheses, as these examples do.

    Checkpoint 7 of 9· Fill the gap

    Only Bob should remain from the table of Alice (2, Math), Bob (5, Physics) and Charlie (7, Chemistry): he is older than 3 and studies Physics. Which operator joins the two conditions?

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

    Sources384

    5.Splitting a string column into an array with split

    split turns a delimited string into an array of strings. It is usually the first step before exploding values packed into one field, such as "red,green,blue" in a tags column. It comes from pyspark.sql.functions, not from the DataFrame. You use it inside select or withColumn, and it returns a Column.

    The pattern is a Java regular expression, not a plain delimiter. '[ABC]' splits on any of the letters A, B or C. A delimiter character that has a special meaning in regex syntax is read as regex, not as the literal character. Write such a pattern as a regular expression that matches the delimiter literally.

    split with no limit, a positive limit and a non-positive limitpython
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',])
    df.select('*', dbf.split(df.s, '[ABC]')).show()
    df.select('*', dbf.split(df.s, '[ABC]', 2)).show()
    df.select('*', dbf.split('s', '[ABC]', -2)).show()

    The optional limit controls how many times the pattern is applied. With limit > 0, the array has at most limit elements, and the last element holds everything after the last match. With limit <= 0, the pattern is applied as many times as possible and the array can be any length. A positive limit is useful when only the first fields of a string are structured, for example splitting a log line into a level and the rest of the message.

    Checkpoint 8 of 9· Fill the gap

    The third call passes an explicit limit, but the pattern should still be applied as many times as possible, with no cap on how many elements the array has. Which value completes it?

    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',])
    df.select('*', dbf.split(df.s, '[ABC]')).show()
    df.select('*', dbf.split(df.s, '[ABC]', 2)).show()
    df.select('*', dbf.split('s', '[ABC]',  ? )).show()

    Sources9

    6.Turning array elements into rows with explode and explode_outer

    explode returns one output row per element of an array, or per entry of a map. Each output row carries copies of the input row's other columns, so an order row with three items becomes three rows. If you don't alias the result, an exploded array goes into a column named col. An exploded map produces two columns, key and value.

    explode drops the rows whose array is empty or nullpython
    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|
    +---+---------------+----+

    Rows 2 and 3 are gone. A NULL element inside an array still produces a row, but an empty or null array produces none, so explode silently drops those records. Suppose you explode a customer table on phone_numbers. Every customer without a phone number disappears from the output, and a later count of customers comes up short.

    explode_outer keeps those rows. When the array or map is null or empty, it produces a single row with NULL in the new column, so every input row appears at least once. Use explode when rows without elements are useless downstream. Use explode_outer when every original record must stay in the output.

    explode_outer keeps empty and null arrays as a NULL rowpython
    from pyspark.sql import functions as sf
    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|
    +---+---------------+----+
    What each function returns for one input row
    Input value of aexplodeexplode_outer
    [1, 2, 3, NULL]4 rows: 1, 2, 3, NULL4 rows: 1, 2, 3, NULL
    [] (empty)No row1 row with col NULL
    NULLNo row1 row with col NULL

    Only one explode is allowed per SELECT clause. To explode two array columns, chain two select calls and give each exploded column its own alias. The result contains every combination of elements, so exploding [1, 2] and [3, 4, 5] this way gives six rows. When the array holds structs, alias the exploded column and select "s.*" to turn the struct's fields into ordinary columns.

    Two explodes need two selects, and the result is every combination of elementspython
    import pyspark.sql.functions as sf
    df = spark.sql('SELECT ARRAY(1,2) AS a1, ARRAY(3,4,5) AS a2')
    df.select(
        '*', sf.explode('a1').alias('v1')
    ).select('*', sf.explode('a2').alias('v2')).show()

    Checkpoint 9 of 9· Fill the gap

    In this output, the input rows i=2 (empty array) and i=3 (NULL array) produce no rows at all, while the NULL element inside i=1's array still gets its own row. Which function was called?

    df.show()
    
    +---+---------------+
    |  i|              a|
    +---+---------------+
    |  1|[1, 2, 3, NULL]|
    |  2|             []|
    |  3|           NULL|
    +---+---------------+
    
    df.select('*', sf. ? ('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|
    +---+---------------+----+

    Sources1011

    Sources

    (11)

    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 4
    2. 2.
      “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 expressions and returns a new DataFrame.”
      ↩︎ Adding and replacing columns with withColumn
      “Alias for filter.”
      ↩︎ Exam trap 2
    4. 4.
      “df_casted = df_customer.withColumn("c_custkey", col("c_custkey").cast(StringType()))”
      ↩︎ Adding and replacing columns with withColumn
      “use the withColumnRenamed method, which accepts the existing and new column names”
      ↩︎ Renaming columns with withColumnRenamed and alias
      “The alias method is especially helpful when you want to rename your columns as part of aggregations”
      ↩︎ Renaming columns with withColumnRenamed and alias
      “You can also drop multiple columns at once:”
      ↩︎ Dropping columns with drop
      “& and | enable you to AND and OR conditions, respectively.”
      ↩︎ Filtering rows with filter and where
      “The alias method is especially helpful when you want to rename your columns as part of aggregations:”
      ↩︎ Checkpoint
    5. 5.
      “This is a no-op if the schema doesn't contain the given column name.”
      ↩︎ Renaming columns with withColumnRenamed and alias
      “This is a no-op if the schema doesn't contain the given column name.”
      ↩︎ Exam trap 1
    6. 7.
      “This is a no-op if the schema doesn't contain the given column name(s).”
      ↩︎ Dropping columns with drop
      “When an input is a column name, it is treated literally without further interpretation. Otherwise, it will try to match the equivalent expression.”
      ↩︎ Dropping columns with drop
      “Returns a new DataFrame without specified columns. This is a no-op if the schema doesn't contain the given column name(s).”
      ↩︎ Checkpoint
    7. 9.
      “The regex string should be a Java regular expression.”
      ↩︎ Splitting a string column into an array with split
      “The resulting array's length will not be more than limit”
      ↩︎ Splitting a string column into an array with split
      “the resulting array's last entry will contain all input beyond the last matched pattern”
      ↩︎ Splitting a string column into an array with split
      “pattern will be applied as many times as possible, and the resulting array can be of any size.”
      ↩︎ Splitting a string column into an array with split
    8. 10.
      “Uses the default column name col for elements in the array and key and value for elements in the map unless specified otherwise.”
      ↩︎ Turning array elements into rows with explode and explode_outer
      “Only one explode is allowed per SELECT clause.”
      ↩︎ Turning array elements into rows with explode and explode_outer
    9. 11.
      “Unlike explode, if the array/map is null or empty then null is produced.”
      ↩︎ Turning array elements into rows with explode and explode_outer
      “Unlike explode, if the array/map is null or empty then null is produced.”
      ↩︎ Exam trap 3

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

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