Typorithm · medium

withColumn

df-withcolumnsparkwithColumnrenameimmutable
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn withColumn

0%

DataFrames

withColumn derives a new column from an expression; withColumnRenamed changes a column's name. Both return a brand-new DataFrame — the original stays untouched, because DataFrames are immutable.

withColumn("adult", col("age") >= 18) adds a column whose value comes from a per-row expression; if the name already exists it replaces that column.

withColumnRenamed("name", "fullName") takes the old name then the new name and returns a DataFrame with the column relabelled.

Crucially, both methods are immutable: they return new DataFrames rather than mutating the original, so chaining them composes cleanly.

01

withColumn derives or replaces a column from an expression.

02

withColumnRenamed relabels a column (old, new).

03

Both return new DataFrames; the original is unchanged.

df.withColumn("adult", col("age") >= 18).withColumnRenamed("name", "fullName");

Read the implementation

Connect each part of the code to the concept before you type.

1. Derive a column

withColumn adds a new "adult" column computed from the col("age") >= 18 expression.

df.withColumn("adult", col("age") >= 18)

2. Column expression

The expression produces a boolean per row, becoming the value of the new column.

col("age") >= 18

3. Rename a column

withColumnRenamed changes a column's name, returning a new DataFrame.

.withColumnRenamed("name", "fullName")

4. Old then new

The first argument is the existing name, the second is the new name.

"name", "fullName"

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

withColumn: Lesson & Practice · Typorithm | ApplyDjinn