AnalystPath

Pivot Sensor Readings Into One Row Per Device

PandasHardSenior level~10 min

Problem

You are given one DataFrame `readings` with columns `device_id`, `gauge`, and `value`, where `gauge` is the name of a measurement station and `value` is the reading that device produced at that station. There is at most one reading per `(device_id, gauge)`.

Reshape the data into a wide format: output `device_id` as the first column, then one column for each distinct gauge name (sorted alphabetically), holding that device's `value` at that gauge, or `None` if the device has no reading there. For this dataset the gauges are `Alpha`, `Bravo`, `Delta`, `Echo`. Return one row per device.

Input data

Example rows — the live problem includes the full dataset.

readings
device_idgaugevalue
1Alpha12
1Delta40
2Bravo7
2Echo55
3Alpha9

Expected output

Your answer should return 3 rows with the columns device_id, Alpha, Bravo, Delta, Echo.

Starter code (Pandas (Python))

import pandas as pd

def pivot_readings(readings) -> pd.DataFrame:
    # Your code here
    return readings

Solve this Pandas question free

Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related Pandas questions