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.
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.
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|
# +---+-----+----+withColumn takes a column name and a Column expression. It returns a new DataFrame with the full row plus the new column. select would keep only the expressions you list. withColumns takes one dict, not a name and an expression. withColumnRenamed takes two strings and only renames a column.
Source: docs.databricks.comCheckpoint 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?
Each withColumn call adds a projection, so a loop builds a large plan. withColumns with a dict, or one select listing every column, adds all the columns in a single step.
“calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans which can cause performance issues”Source: docs.databricks.com
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?
Correct answer: A — orders_df = orders_df.withColumn("total", col("price") * col("quantity"))
- A.
withColumnreturns a new DataFrame with the named column added when it does not already exist, or replaced when it does, so reassigning the result correctly produces the computed field. This is the standard way to derive a new column from an expression built out of existing columns. - B. Spark DataFrames are immutable and do not support item assignment the way pandas DataFrames do, so this bracket-assignment syntax raises an error rather than mutating or creating a column. There is no
__setitem__behavior defined onDataFrame. - C.
withColumnRenamedonly accepts two string arguments, the existing column name and the new name, and does not accept a third expression argument, so this call fails with a signature error. It also renames a column rather than computing a new value from an expression. - D. Passing the bare string
"price * quantity"toselecttreats it as a plain string literal column name rather than a SQL expression, so this does not compute the product; the string would need to be wrapped inexpr(...)to be parsed as an expression.
Checkpoint 4 of 9· Exam question
Which statement accurately distinguishes the DataFrame withColumns method from chaining several separate withColumn calls?
Correct answer: A — withColumns accepts a dictionary of column names mapped to expressions and applies every addition or replacement in one call, instead of calling withColumn repeatedly.
- A.
withColumnsaccepts a dictionary of column name toColumnexpression pairs and applies all of the additions or replacements in a single planned step, which is functionally equivalent to but more concise than repeatedwithColumncalls. This is the current, supported API for adding several columns at once. - B. Both
withColumnsandwithColumncan add brand new columns from an expression, not just rename existing ones; renaming is instead the job ofwithColumnRenamed, so this description of the restriction is incorrect. - C.
withColumnsis a current, actively documented DataFrame method and has not been removed; it remains available alongsidewithColumnfor adding or replacing one or more columns. - D. Neither method triggers eager execution or writes to storage; both
withColumnsandwithColumnonly build up a lazy transformation plan that executes when an action such asshow,count, orwriteis called.
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.
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.
| Method | Changes | If the named column is missing |
|---|---|---|
| withColumn / withColumns | Adds a column, or replaces the values of one with the same name | Adds it as a new column |
| withColumnRenamed / withColumnsRenamed | Column names only | No-op: DataFrame returned unchanged |
| drop | Removes columns; others untouched | No-op: DataFrame returned unchanged |
| filter / where | Which rows are kept; schema unchanged | Not 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?
If no column matches the existing name, withColumnRenamed does nothing and returns the same DataFrame without raising an error. The typo isn't caught here. It shows up later, when a downstream step looks for customer_key and can't find it.
“This is a no-op if the schema doesn't contain the given column name.”Source: docs.databricks.com
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?
Correct answer: A — Call customers_df.drop("internal_notes") and write the returned DataFrame, since drop returns a new DataFrame with the named column removed and leaves all other columns untouched.
- A.
dropaccepts one or more column names orColumnobjects and returns a new DataFrame with those columns removed from the schema while every remaining column is preserved, which is exactly what a sensitive-column removal step needs. - B.
filter(orwhere) removes rows based on a boolean condition; it changes which rows are kept, not which columns exist in the schema, so the sensitive column would still be present in the output. - C. Assigning a null literal with
withColumnreplaces every value in that column withnull, it does not remove the column from the schema, so the sensitive field would remain present with empty values. - D.
dropDuplicatesremoves duplicate rows based on the given column subset; it has no effect on which columns appear in the resulting schema, so the sensitive column would still be included.
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.
> 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?
withColumn replaces the values of a column that already has the given name, so tags becomes the array that split produces. It returns a new DataFrame, so raw_df keeps its original string column.
“Returns a new DataFrame by adding a column or replacing the existing column that has the same name.”Source: docs.databricks.com
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.
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|
# +---+----+-------+In PySpark you combine Column conditions with & (and) or | (or), and each comparison goes in its own parentheses. With |, Charlie's row would pass too, because age 7 is greater than 3. Python's and doesn't combine Column expressions, and && is not a Python operator.
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.
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.
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.
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.
> 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 SparkCheckpoint 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 Sparkexplode_outer emits one row with NULL when the collection is NULL or empty, so the parent row survives. explode would return only the 10 and 20 rows and drop the NULL row. inline and inline_outer turn arrays of structs into one column per struct field, and this is a plain array of integers.
Source: docs.databricks.comSources
(15)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.
“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“Alias for filter.”
↩︎ Filtering rows with filter and where - 4.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/withColumnRenamedOfficial docs
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/withColumnsRenamedOfficial docs
“A dict of existing column names and corresponding desired column names.”
↩︎ Renaming and dropping columns - 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.
“Splits str around matches of the given pattern.”
↩︎ Splitting a string column into parts - 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 - 9.
“if partNum is out of range of split parts, returns empty string.”
↩︎ Splitting a string column into parts - 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 - 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 - 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 - 13.
“Explodes an array of structs into a table.”
↩︎ Exploding arrays and maps into rows - 14.
“If input is NULL a single row with NULLs for each column is produced.”
↩︎ Exploding arrays and maps into rows - 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