Sub topic 10
Adding and changing columns
This chapter covers how to create new columns and change existing ones on a Spark DataFrame. It assumes you can read basic PySpark code, know what a DataFrame and a column expression are, and have used select and filter. It also assumes you know that transformations are lazy, so nothing runs until an action such as show() or display() is called.
How columns are added in Spark
DataFrames are immutable. No method edits a DataFrame in place. Each method returns a new DataFrame that describes the change, and you assign it to a name to keep it.
The main tool is withColumn(name, expression). It takes the new column's name and a column expression. If the name already exists, the old column is replaced. If it doesn't, a new column is appended at the end.
The examples use the orders DataFrame from earlier chapters. Run this cell first to build it:
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.printSchema()
display(orders)Here withColumn("order_date", ...) reuses an existing name, so it changes the column's type from string to date. The column keeps its position in the schema.
Building new columns from expressions
A new column is computed from other columns, constants, and built-in functions. Use F.lit to turn a Python constant into a column. Without it, Spark treats a bare string as a column name.
enriched = (
orders
.withColumn("amount_with_tax", F.round(F.col("amount") * 1.2, 2))
.withColumn("currency", F.lit("USD"))
.withColumn("order_month", F.date_format("order_date", "yyyy-MM"))
.withColumn("customer_upper", F.upper("customer"))
)
enriched.show()Arithmetic on a null gives null. Carol's amount_with_tax is null because her amount is null.
Conditional logic with when and otherwise
F.when(condition, value) is the DataFrame form of SQL's CASE WHEN. Chain more when calls for more branches, and finish with otherwise for the default.
tiered = orders.withColumn(
"size",
F.when(F.col("amount") >= 100, "large")
.when(F.col("amount") >= 50, "medium")
.when(F.col("amount").isNotNull(), "small")
.otherwise("unknown"),
)
tiered.show()Branches are checked in order, and the first match wins. If you leave out otherwise, rows that match no branch get null. A comparison with a null amount evaluates to null, which counts as not true, so the null row falls through to the isNotNull branch check and then to otherwise.
Replacing nulls while adding a column
F.coalesce returns the first non-null argument. It is the usual way to fill defaults.
filled = orders.withColumn("amount_filled", F.coalesce("amount", F.lit(0.0)))
filled.show()Changing types with cast
cast converts a column to another type. A value that can't be converted becomes null instead of raising an error, as long as ANSI mode is off. ANSI mode is controlled by spark.sql.ansi.enabled, and its default depends on your runtime version. Check the setting if bad values are silently turning into nulls, or if casts suddenly fail.
typed = (
orders
.withColumn("order_id", F.col("order_id").cast("string"))
.withColumn("amount_int", F.col("amount").cast("int"))
)
typed.printSchema()Casting a double to int truncates toward zero. It does not round. Use F.round first if you want rounding.
Renaming and dropping columns
Use withColumnRenamed(old, new) to rename. Renaming a column that doesn't exist does nothing and raises no error, so a typo goes unnoticed until a later step fails. Use drop to remove columns, and note that it also ignores names that don't exist.
cleaned = (
orders
.withColumnRenamed("amount", "order_amount")
.drop("order_id")
)
cleaned.printSchema()Many columns at once
Each withColumn call adds a projection to the query plan. A few calls are fine. Hundreds of calls in a loop make plan analysis slow and can cause stack errors. When you add many columns, use one select, or withColumns in Spark 3.3 and later, which takes a dictionary.
multi = orders.withColumns(
{
"amount_x2": F.col("amount") * 2,
"customer_len": F.length("customer"),
"year": F.year("order_date"),
}
)
multi.show()The select form lists the existing columns and the new ones together:
multi_select = orders.select(
"*",
(F.col("amount") * 2).alias("amount_x2"),
F.length("customer").alias("customer_len"),
F.year("order_date").alias("year"),
)The * keeps every existing column. If you leave it out, only the listed columns survive.
Order matters inside a chain
Each step sees the DataFrame produced by the step before it. A later withColumn can use a column created earlier in the same chain. A column cannot be used inside the same select list that defines it.
chain = (
orders
.withColumn("net", F.col("amount") * 0.9)
.withColumn("net_rounded", F.round("net"))
)
chain.show()If net_rounded were defined in the same select as net, Spark would fail with an unresolved column error.
The shape of the plan
The diagram shows how a chain of column changes passes through Spark. Nothing runs until the final action.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| New column is the literal text you typed | A string was used where a column was expected, or the reverse | Use `F.col("name")` for columns and `F.lit("text")` for constants |
| `AnalysisException: cannot resolve` | Column name misspelled, or used before it exists | Check `df.columns` and the order of steps |
| Value is null after `cast` | The text can't be converted | Inspect the raw values, and decide whether ANSI mode should be on |
| Result unchanged after `withColumn` | Return value was not assigned | Write `df = df.withColumn(...)` |
| Slow planning with many columns | `withColumn` called in a long loop | Use `withColumns` or one `select` |
| `TypeError: Column is not iterable` | A Column was passed where a Python value was expected | Use the Column API, such as `F.when`, and not Python `if` or `and` |
A related trap is combining conditions. Python's and, or and not don't work on columns. Use &, | and ~, and put parentheses around each comparison.
flagged = orders.withColumn(
"flag",
(F.col("amount") > 50) & (F.col("customer") == "alice"),
)
flagged.show()Built-in functions first
Before writing a Python function for a new column, look for a built-in in pyspark.sql.functions. Built-ins run inside Spark's engine and the optimizer understands them. A Python UDF (user-defined function) runs row by row in a separate process and hides the logic from the optimizer. Later chapters cover that cost.
Exercise
Starting from orders, add a column status that is "missing" when amount is null, "high" when amount is at least 100, and "normal" otherwise. Which function is required to make the default case work, and what happens to rows if you omit it?
Show answer
Use F.when(F.col("amount").isNull(), "missing").when(F.col("amount") >= 100, "high").otherwise("normal") inside withColumn("status", ...). The otherwise call supplies the default. Without it, rows that match no when branch get null in status. Check the null case first, because a comparison with null is not true and would otherwise fall to the default.
Exercise
A loop calls withColumn 400 times to add columns, and the cell spends a long time before any data is processed. What is the cause, and how do you fix it?
Show answer
Each withColumn adds another projection to the logical plan, so analysis and optimization of the deep plan become slow. Build the expressions in a dictionary and call withColumns (Spark 3.3 and later), or build a list of columns and use a single select("*", *new_columns).