Sub topic 10
Adding and changing columns
This chapter assumes you can create a DataFrame, read its schema, and use select and filter. You should also know that Spark transformations are lazy. Here you will add and change columns with withColumn and related methods.
How withColumn works
DataFrames are immutable. withColumn(name, expression) does not change the DataFrame you call it on. It returns a new DataFrame with the column added. If name already exists, the new column replaces the old one.
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"))
.withColumn("amount_with_tax", F.round(F.col("amount") * 1.2, 2))
.withColumn("order_month", F.month("order_date"))
)
orders.printSchema()
display(orders)The first call replaces the string order_date with a date. The other two add new columns. Because the result is assigned back to orders, later cells see the changed version. Nothing runs until display triggers an action.
Conditional values
Use F.when(...).otherwise(...) for if/else logic. A chain of when calls works like CASE WHEN in SQL.
orders = orders.withColumn(
"size",
F.when(F.col("amount") >= 100, "large")
.when(F.col("amount") >= 50, "medium")
.otherwise("small"),
)
display(orders)Carol's amount is null. A comparison with null is not true, so her row falls through to otherwise and gets "small". That may be wrong for your data. Add an explicit F.when(F.col("amount").isNull(), "unknown") first if nulls need their own label.
Renaming, casting and dropping
cleaned = (
orders
.withColumnRenamed("amount_with_tax", "gross_amount")
.withColumn("order_id", F.col("order_id").cast("string"))
.drop("order_month")
)
cleaned.printSchema()withColumnRenamed(old, new)renames one column. Ifolddoes not exist, Spark silently does nothing.castchanges a column's type. A value that cannot be converted becomes null, not an error, under default settings.dropremoves columns. Dropping a missing name is also silent.
Common errors
- Forgetting to assign the result. Calling
orders.withColumn(...)alone and discarding the return value changes nothing. - Using a Python value where a column is expected.
withColumn("flag", "yes")fails. Wrap constants inF.lit("yes"). - Many chained
withColumncalls. Each call adds a step to the plan. For dozens of columns, build them in oneselectinstead. - A typo in a column name. Spark raises an
AnalysisExceptionwhen the plan is analyzed, which is often at the line that builds the DataFrame, not at an action.
orders = orders.withColumn("source", F.lit("web"))
multi = orders.select(
"*",
(F.col("amount") * 2).alias("double_amount"),
F.upper("customer").alias("customer_upper"),
)
display(multi)Exercise
A DataFrame has a string column price containing "10.5", "abc" and "7". You run df.withColumn("price", F.col("price").cast("double")). What does the "abc" row contain afterwards, and does the cell fail?
Show answer
The "abc" row contains null. The cell does not fail, because under default settings a failed cast produces null instead of raising an error.