Skip to content
Bronze 6 min read · Selection 3 practice problems ↓

withColumn

Data rarely arrives with every column you need. You add a tax column, fix a type, clean a name. withColumn adds or replaces one column at a time; withColumns does several at once. This lesson shows both, how they differ from renaming, and why a long loop of them slows Spark down.

Step 1 · PySpark functions · Bronze · Read and select, lesson 4 of 5

Read first: select (skip if you know it)

In plain words first

Imagine adding a column to a printed spreadsheet with a pen: "amount with tax" next to "amount". Every other column stays as it was. If you write into a column that already exists, you cross out the old values and write the new ones in the same place.

That is withColumn: keep everything, add or replace one column. withColumns is the same with several pens at once.

What it does

It keeps every existing column and appends a new one at the end. If a column with that name already exists, it is replaced in place, keeping its position.

PySparkSpark SQL
employees.withColumn("tax", F.col("salary") * 0.3)
SELECT *, salary * 0.3 AS tax FROM employees

Step by step

Input

namesalary
Asha72000
Ben48000

Output

namesalaryband
Asha72000high
Ben48000standard

A new column computed from an existing one. The original DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → is unchanged; you get a new one back.

Run the example

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
from pyspark.sql import functions as F
result = (employees
    .withColumn("band", F.when(F.col("salary") >= 60000, "high").otherwise("standard"))
    .withColumn("salary", F.col("salary").cast("double"))   # replaces in place
    .withColumnRenamed("dept", "department"))
SELECT id, name, dept AS department,
       CAST(salary AS DOUBLE) AS salary, manager_id,
       CASE WHEN salary >= 60000 THEN 'high' ELSE 'standard' END AS band
FROM employees

Notice how the SQL version has to list every column to replace one. That convenience is exactly what withColumn gives you.

Several columns at once: withColumns

Since Spark 3.3, withColumns takes a dictionary of {name: column} and applies all of them in one step. In one call you can compute a new column, add a constant and modify an existing column:

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
from pyspark.sql import functions as F
result = employees.withColumns({
    "monthly_pay": F.round(F.col("salary") / 12, 2),   # computed
    "status": F.lit("active"),                          # constant
    "name": F.upper(F.col("name")),                     # modifies an existing column
})
SELECT id,
       upper(name)              AS name,
       dept, salary, manager_id,
       round(salary / 12, 2)    AS monthly_pay,
       'active'                 AS status
FROM employees
  • New names are added at the end, in the order of the dictionary; an existing name (name here) is replaced in place.
  • Constants must be wrapped: F.lit("active"), not "active", which Spark would read as a column name.
  • You can also import the functions directly: from pyspark.sql.functions import col, lit, upper, then write col("salary").
Watch out: every expression in one withColumns call is computed from the input DataFrame. A column created in the same call cannot be used yet: withColumns({"bonus": F.col("salary") * 0.1, "total": F.col("salary") + F.col("bonus")}) fails because bonus does not exist until the call has finished. Put dependent columns in a second call, or chain withColumn.

The withColumn family

MethodWhat it doesSince
withColumn(name, col)Add or replace one column.1.3
withColumns({name: col, ...})Add or replace several columns in one projection.3.3
withColumnRenamed(old, new)Rename one column. Does nothing if old does not exist, so typos fail silently.1.3
withColumnsRenamed({old: new})Rename several columns.3.4
drop("a", "b")Remove columns. Also silent for names that do not exist.1.4

The loop problem Optional deep dive

Each call wraps the plan in one more Project node. In a loop over hundreds of columns that produces a plan hundreds of levels deep. Spark re-analyses the whole plan on every call, so the cost grows roughly with the square of the number of calls: jobs that should take seconds spend minutes on the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more → before a single tasktask: The work for one partition in one stage, run on one CPU core. Learn more → starts.

PySpark · Slow, then fast
cols = ["name", "city", "email"]    # the string columns to trim

# Slow: one projection per column
for c in cols:
    df = df.withColumn(c, F.trim(F.col(c)))

# Fast: one projection for all of them
df = df.withColumns({c: F.trim(F.col(c)) for c in cols})
Note: The Spark documentation itself warns against calling withColumn many times in a loop and recommends select with multiple columns instead.

Casting safely

.cast("int") on a string that is not a number returns null in Spark 3, silently. In Spark 4.0, with ANSI mode on by default, the same cast raises an error. If you expect bad values, use try_cast (SQL, or F.expr("try_cast(x AS INT)")), which always returns null on failure, and count the nulls afterwards.

Common mistakes

  • Expecting withColumn to modify the DataFrame — df.withColumn("annual_pay", F.col("salary") * 12) on its own line leaves df without an annual_pay column. Assign the result: df = df.withColumn(...).
  • Renaming a column that does not exist — withColumnRenamed("salry", "salary") returns the DataFrame unchanged, with no error. Check df.columns after renaming.
  • Generating hundreds of withColumn calls — A loop adding 400 columns spends minutes on the driver before a single task runs. Use withColumns or one select.
  • Referring to a column created in the same withColumns call — In withColumns({"net": ..., "tax": F.col("net") * 0.2}), net does not exist yet: every expression sees the input DataFrame. Use a second call.

Key takeaways

  • withColumn appends a new column at the end, or replaces an existing one in place, keeping its position.
  • Wrap constants: F.lit("active"), not "active", which Spark reads as a column name.
  • When bad values are expected in a cast, use try_cast (Spark 4.0 makes .cast fail on them) and count the nulls afterwards.

Interview prep

THE QUESTION

"A job adds 400 derived columns in a for loop and spends 20 minutes before any task runs. Why?"

Every withColumn adds a projection, and the analyzer re-processes the growing plan each time, so driver-side planning dominates. Replace the loop with one select or withColumns, and confirm by watching the Spark UI: no stages appear until planning ends.

Avoid: "Spark is slow at adding columns". The cost is on the driver, analysing an ever-deeper plan, not in the executors.

Follow-ups · answer out loud, then open

Follow-up"What does withColumns do differently?"
withColumns (Spark 3.3+) takes a dict of name to expression and adds them in one projection, so the plan grows by one step instead of one per column. It is the drop-in fix for the loop.
Scenario"withColumn('total', col('price') * col('qty')) gives null for some rows. What do you check?"
Nulls in either input: any arithmetic with null is null. Decide whether missing means zero (F.coalesce(F.col("qty"), F.lit(0))) or whether those rows are bad data to report. Also check types: a string price cast to a number becomes null on bad values.
Trap"withColumn with an existing name adds a second column with the same name."
No. It replaces the existing column in place, keeping its position. Use a new name if you need both.

Check yourself

4 questions

What does df.withColumn("salary", F.col("salary") * 2) do when salary exists?

Show the answer

Replaces salary in place with the doubled value. withColumn replaces a column with the same name and keeps its position.

What happens with df.withColumnRenamed("slary", "pay") if there is no column slary?

Show the answer

Nothing: the DataFrame comes back unchanged. withColumnRenamed is a no-op for names that do not exist, which is why typos go unnoticed.

What happens with df.withColumns({"a": F.col("x") * 2, "b": F.col("a") + 1}) when df has no column a?

Show the answer

It fails: a does not exist yet, because every expression is computed from the input DataFrame. withColumns evaluates all expressions against the input DataFrame. Dependent columns need a second call.

Which is the best way to trim 200 string columns?

Show the answer

df.withColumns({c: F.trim(F.col(c)) for c in cols}). withColumns (or one select) builds a single projection, so planning stays fast.

Practise this

Problems that use withColumn, graded on hidden tests

See all 35 problems →

Keep going

Up next · Read and select · lesson 5 of 5 · 4 min read
orderBy
Sort rows ascending or descending, control where nulls go, and know what a global sort costs.

Related lessons

Previous: filter / where

Primary sources: DataFrame.withColumn · DataFrame.withColumns