2. Add a Bonus Column
Difficulty: Easy · Topics: Filtering & Selection
Add two new columns to employees:
bonus— 10% ofsalarytotal_comp—salaryplusbonus
Return the columns id, name, salary, bonus, total_comp. If salary is null, both new columns should be null.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
employees
| id | name | salary |
|---|---|---|
| 1 | Asha | 72000 |
| 2 | Ben | 48000 |
| 3 | Chitra | 95000 |
Expected output
| id | name | salary | bonus | total_comp |
|---|---|---|---|---|
| 1 | Asha | 72000 | 7200 | 79200 |
| 2 | Ben | 48000 | 4800 | 52800 |
| 3 | Chitra | 95000 | 9500 | 104500 |
Hints
Hint 1
withColumn("bonus", F.col("salary") * 0.1) creates a new column.Hint 2
A column you just created can be used by the nextwithColumn.Hint 3
Arithmetic with null gives null automatically.Learn the concepts
- withColumn · 6 min read. Add or replace one column, and why calling it in a long loop slows Spark down.
PySpark functions you'll practise
- withColumn
Related problems
- Filter High Earners · Easy · Filtering & Selection
- Distinct User Actions · Easy · Filtering & Selection
- Build a Price List · Easy · Filtering & Selection
- Paid Orders in March · Easy · Filtering & Selection
- Sort Delivery Options · Easy · Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice