← All Python interview questions
Unpivot a wide survey export into tidy rows
MediumPandas — CleaningDeloitteNielsen
The survey tool exports one column per question. Analysis needs tidy long format instead.
Write tidy(df) that melts the q1, q2 and q3 columns into question/score pairs, keeps respondent, drops rows with a missing score, and returns the result sorted by respondent then question with a reset index.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
import numpy as np
survey = pd.DataFrame({
"respondent": ["r1", "r2", "r3"],
"q1": [5, 4, np.nan],
"q2": [3, np.nan, 2],
"q3": [4, 5, 5],
})- Step 1: `melt` is the inverse of `pivot`: `id_vars` stay as identifying columns while `value_vars` collapse into two columns.
- Step 2: `var_name` and `value_name` name the output columns explicitly instead of accepting the default `variable`/`value`.
- Step 3: `dropna(subset=['score'])` removes unanswered questions — in wide format those were invisible `NaN` cells.
- Step 4: Sorting and resetting the index gives a stable frame that is safe to join or export.
def tidy(df):
out = df.melt(
id_vars="respondent",
value_vars=["q1", "q2", "q3"],
var_name="question",
value_name="score",
)
out = out.dropna(subset=["score"])
return out.sort_values(["respondent", "question"]).reset_index(drop=True)Learn the concept first
Stuck on Pandas — Cleaning? These free Python lessons teach it step by step.
More Pandas — Cleaning questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program