posexplode
Order inside a list often matters: the first stop of a delivery route, the third step of a funnel. explode throws that position away. posexplode keeps it as a column. This lesson shows how, how to keep empty lists, and how to put an array back together in the right order.
Step 1 · PySpark functions · Silver · Arrays and nested data, lesson 2 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: explode (skip if you know it)
In plain words first
Unpacking a numbered train route into one card per station, you write the stop number on each card: 1 for the first station, 2 for the second. Later you can still tell which station came first, sort the cards back into order, or pick only the third stop.
posexplode is explode plus that stop number, called pos, which starts at 0.
What it does
An arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → has an order: the third stop of a trip means something. explodeexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more → throws that order away. posexplode keeps it as a column, so you can filter, join or sort on the position.
Step by step
routes
| trip | stops |
|---|---|
| T1 | [Pune, Lonavala, Mumbai] |
| T2 | [Delhi, Agra] |
| T3 | [] |
posexplode
| trip | pos | stop |
|---|---|---|
| T1 | 0 | Pune |
| T1 | 1 | Lonavala |
| T1 | 2 | Mumbai |
| T2 | 0 | Delhi |
| T2 | 1 | Agra |
Positions start at 0. T3 disappears because its array is empty.
Run the example
Input: routes
| trip | stops |
|---|---|
| T1 | [Pune, Lonavala, Mumbai] |
| T2 | [Delhi, Agra] |
| T3 | [] |
from pyspark.sql import functions as F result = routes.select("trip", F.posexplode_outer("stops").alias("pos", "stop"))
SELECT trip, pos, stop FROM routes LATERAL VIEW OUTER posexplode(stops) t AS pos, stop
This uses the _outer variant, so T3 survives with nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → pos and stop. Note alias with two names: a generator that outputs two columns takes one alias per column.
What the position is good for
- First, last or nth element as rows: filter
pos == 0. For a single value,element_at(arr, 1)(1-based) orarr[0]is simpler. - Consecutive pairs: posexplode, then self-join on
a.pos + 1 = b.posto get each (stop, next stop) leg of a trip. - Parallel arrays: two arrays where element i of one belongs with element i of the other. Explode one with positions and pick from the other with
element_at(other, pos + 1), or zip them first witharrays_zipand explode once.
Putting an array back together in order
After changing the exploded rows, you often need the arrays back. A plain collect_list does not keep the original order, because rows can arrive from different taskstask: The work for one partition in one stage, run on one CPU core. Learn more → in any order. The position fixes this: collect (pos, stop) pairs, sort them (a structstruct: A column that holds a small record with named fields, like an address with a city and a pin code. Learn more → sorts by its first field, pos), then keep only the stop of each pair.
stops = routes.select("trip", F.posexplode("stops").alias("pos", "stop")) changed = stops.withColumn("stop", F.upper("stop")) # any per-row change rebuilt = (changed.groupBy("trip") .agg(F.sort_array(F.collect_list(F.struct("pos", "stop"))).alias("pairs")) .select("trip", F.col("pairs.stop").alias("stops")))
F.transform("stops", lambda s: F.upper(s)) keeps the array and its order with no shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → and no regrouping.Common mistakes
- Assuming positions start at 1 — posexplode is 0-based; element_at is 1-based.
- Losing empty arrays — Use posexplode_outer when every parent row must remain.
- Exploding two arrays separately — Two explodes give a cross product. Zip them, or use positions.
Key takeaways
- posexplode returns each element with its 0-based position.
- posexplode_outer keeps empty and null arrays.
- Positions enable nth-element filters, consecutive pairs and parallel arrays.
- Rebuild ordered arrays with sort_array over (pos, value) structs.
Interview prep
THE QUESTION
"Each trip has an ordered array of stops. Produce one row per leg: from, to."
a.pos + 1 = b.pos. Alternatively, explode with positions and use lead(stop) over a window by trip ordered by pos, which avoids the join. Mention that legs need at least two stops.Avoid: exploding without positions and hoping the order survives. Use posexplode so each stop keeps its index.
Follow-ups · answer out loud, then open
Follow-up"Is pos 0-based or 1-based?"
Scenario"Find the first and last stop of each trip."
F.element_at("stops", 1) and F.element_at("stops", -1). Explode only when you need one row per element.Trap"posexplode on an empty array returns one row with pos 0."
Check yourself
3 questionsWhat is the position of the first element from posexplode?
Show the answer
0. posexplode is 0-based.
Which keeps a trip whose stops array is empty?
Show the answer
posexplode_outer. The _outer variant emits one row with nulls for an empty array.
How do you name both output columns of posexplode?
Show the answer
.alias("pos", "stop"). Multi-column generators accept one alias per output column.
Practise this
Problems that use posexplode, graded on hidden tests
Keep going
Up next · Arrays and nested data · lesson 3 of 5 · 4 min readcollect_list / collect_set
Gather the values of a group into an array, with or without duplicates, and in which order.
Related lessons
Previous: explode
Primary sources: functions.posexplode · functions.posexplode_outer