35. Item Positions in a Basket (POSEXPLODE)
Difficulty: Medium · Topics: Arrays, Filtering & Selection
Each row of baskets has an order_id and items, an array in the order the items were scanned.
Return one row per item: order_id, position (1 for the first item) and item. Orders with an empty or missing basket produce no rows.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
baskets
| order_id | items |
|---|---|
| 1 | [milk, bread, eggs] |
| 2 | [tea] |
Expected output
| order_id | position | item |
|---|---|---|
| 1 | 1 | milk |
| 1 | 2 | bread |
| 1 | 3 | eggs |
| 2 | 1 | tea |
Hints
Hint 1
F.explode loses the position; F.posexplode returns it as well (0-based).Hint 2
Name both outputs:F.posexplode("items").alias("pos", "item").Hint 3
Add 1 to make positions start at 1.Learn the concepts
- posexplode · 3 min read. Explode an array and keep each element position, plus the _outer variant that keeps empty arrays.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
PySpark functions you'll practise
- posexplode
- select
Related problems
- Word Count · Medium · Arrays, Aggregations, Strings, Filtering & Selection
- Keep Users with No Interests (EXPLODE_OUTER) · Medium · Arrays, Filtering & Selection
- Learning Path per Student · Medium · Arrays, Aggregations, Strings, Filtering & Selection
- Sorted Distinct Purchase List · Medium · Arrays, Aggregations
- Data Quality: Null Count per Column · Medium · Null Handling, 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