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.
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.
| Method | What 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|
# +---+-----+----+withColumn takes a new column name and a Column expression. It returns all existing columns plus the new one. select would return only the expressions you list. withColumnRenamed only changes a column's name and cannot compute a value. withColumns expects a single dict that maps names to expressions, not a name and an expression as two arguments.
Source: docs.databricks.comCheckpoint 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?
Correct answer: C — withColumn
- A. select projects a set of column expressions but does not take a target column name and a value expression as two positional arguments the way this call is written, so this signature does not fit.
- B. withColumnRenamed only accepts an existing column name and a new name string; it cannot evaluate a when/otherwise expression, so it cannot produce a computed column.
- C. withColumn takes a target column name and a Column expression, adding the result as a new column while returning a new DataFrame, which matches this call exactly.
- D. filter restricts which rows are kept based on a boolean condition; it does not add or compute a new column, so it does not fit this signature.
- E. withColumnsRenamed takes a dictionary mapping existing names to new names for bulk renaming, not a name plus a computed expression, so it does not match this call.
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.
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?
alias is called on a Column, so it names the aggregate expression when it is created. withColumnRenamed and withColumnsRenamed are DataFrame methods that rename columns which already exist. They cannot be called on an expression, and renaming before the groupBy does not name the computed average.
“The alias method is especially helpful when you want to rename your columns as part of aggregations:”Source: docs.databricks.com
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?
Correct answer: B — df2 ends up identical to df because withColumnRenamed found no column named customer_name to rename.
- A. Spark's rename method matches the first argument against actual column names, not positions, so this description of how the match happens is incorrect.
- B. withColumnRenamed looks for a column matching its first argument; since no column is named customer_name, it silently returns an unchanged DataFrame rather than touching cust_nm.
- C. This method does not validate that the first argument matches a real column, so it never throws an exception when the name is absent; it simply performs a no-op.
- D. withColumnRenamed only relabels an existing column in place; it never fabricates a new column of nulls, so this outcome does not occur.
- E. There is no separate driver-only schema cache that can diverge from the actual data; the returned DataFrame's schema and data are always consistent with each other.
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.
df = spark.createDataFrame(
[(14, "Tom"), (23, "Alice"), (16, "Bob")], ["age", "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|
# +---+------+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?
drop ignores a name that is not in the schema and raises no error, but it still removes the names that do match. phone is dropped, and email stays because the typo matched nothing. The remaining columns keep their original order.
“Returns a new DataFrame without specified columns. This is a no-op if the schema doesn't contain the given column name(s).”Source: docs.databricks.com
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?
Correct answer: D — ['customer_id', 'signup_date']
- A. This list still includes email, but drop was called with email as one of the two column names to remove, so email should not remain in the result.
- B. This list contains only the two dropped names and omits the columns that were kept, which is the opposite of what drop returns.
- C. This is the full original schema; drop was called with two column names as arguments, so both of those columns must be removed from the returned DataFrame.
- D. drop("email", "phone") removes both named columns and returns a new DataFrame retaining every other column in its original order, leaving customer_id and signup_date.
- E. This list still includes phone, but drop was called with phone as one of the two column names to remove, so phone should not remain in the result.
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.
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.
df_customer.filter((col("c_custkey") == 412446) | (col("c_custkey") == 412447)): two comparisons, each in parentheses, joined by |.
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|
# +---+----+-------+Column conditions are combined with & for AND and | for OR, with each comparison in its own parentheses. With | the filter would keep everyone older than 3 or studying Physics, so Charlie would stay too. Python's and and C-style && are not the operators the lesson uses to combine Column conditions.
Source: docs.databricks.com5.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.
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.
Two elements. The first is one. The second holds everything after that first match, twoBthreeC.
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()Any limit of 0 or less applies the pattern as many times as possible, so -2 gives an array of any length. A positive limit such as 1, 2 or 3 caps the array at that many elements and puts the rest of the string in the last element.
Source: docs.databricks.comSources9
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.
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.
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|
+---+---------------+----+| Input value of a | explode | explode_outer |
|---|---|---|
| [1, 2, 3, NULL] | 4 rows: 1, 2, 3, NULL | 4 rows: 1, 2, 3, NULL |
| [] (empty) | No row | 1 row with col NULL |
| NULL | No row | 1 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.
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|
+---+---------------+----+explode returns one row per array element, including a NULL element, but an empty or null array has no elements, so i=2 and i=3 disappear. explode_outer would have kept them as rows with col NULL. split turns a string into an array and does not produce extra rows.
Source: docs.databricks.comSources
(11)
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 4 - 2.
“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 expressions and returns a new DataFrame.”
↩︎ Adding and replacing columns with withColumn“Alias for filter.”
↩︎ Filtering rows with filter and where“Alias for filter.”
↩︎ Exam trap 2 - 4.https://docs.databricks.com/aws/en/pyspark/basicsOfficial docs
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/withColumnRenamedOfficial docs
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/withColumnsRenamedOfficial docs
“A dict of existing column names and corresponding desired column names.”
↩︎ Renaming columns with withColumnRenamed and alias - 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 - 8.
“A Column of BooleanType or a string of SQL expressions.”
↩︎ Filtering rows with filter and where - 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 - 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 - 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