8. Categorize Orders
Difficulty: Easy · Topics: Conditional Logic, Filtering & Selection
Classify every row of orders into a tier:
"High"ifamount >= 1000"Medium"ifamount >= 500"Low"otherwise (including a missing amount)
Return order_id and tier.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
orders
| order_id | customer | amount |
|---|---|---|
| 1 | Asha | 1500 |
| 2 | Ben | 500 |
| 3 | Chitra | 499 |
| 4 | Dev | 1000 |
| 5 | Esha | null |
Expected output
| order_id | tier |
|---|---|
| 1 | High |
| 2 | Medium |
| 3 | Low |
| 4 | High |
| 5 | Low |
Hints
Hint 1
F.when(cond, value).when(cond2, value2).otherwise(default) works like a CASE expression.Hint 2
Order matters: conditions are checked top to bottom.Hint 3
A null amount makes every condition null, so it falls through tootherwise.Learn the concepts
- when / otherwise · 4 min read. CASE WHEN logic inside a column: first match wins, and a missing otherwise means null.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
- 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
- when / otherwise
- select
- withColumn
Related problems
- Label Late Shipments · Easy · Dates, Null Handling, Conditional Logic
- Filter High Earners · Easy · Filtering & Selection
- Add a Bonus Column · Easy · Filtering & Selection
- Distinct User Actions · Easy · Filtering & Selection
- Build a Price List · 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