Skip to content

27. Forward-Fill Missing Readings

Difficulty: Hard · Topics: Window Functions

IoT sensors sometimes send a reading with no temperature. Replace each missing temp with the most recent earlier reading from the same sensor.

A sensor's leading readings before its first real value stay null. Return sensor_id, ts, temp.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

readings

sensor_idtstemp
s12024-01-01 00:00:0020.5
s12024-01-01 01:00:00null
s12024-01-01 02:00:00null
s12024-01-01 03:00:0022
s22024-01-01 00:00:0018
s22024-01-01 01:00:00null

Expected output

sensor_idtstemp
s12024-01-01 00:00:0020.5
s12024-01-01 01:00:0020.5
s12024-01-01 02:00:0020.5
s12024-01-01 03:00:0022
s22024-01-01 00:00:0018
s22024-01-01 01:00:0018

Hints

Hint 1Partition by sensor, order by timestamp, and look at all rows from the start up to the current one.
Hint 2F.last("temp", ignorenulls=True) over that frame returns the latest non-null value.
Hint 3The frame is .rowsBetween(Window.unboundedPreceding, Window.currentRow).

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems