Reshape wide panel data to long format with pandas wide_to_long
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `wide_to_long_panel(df)` that reshapes a wide panel DataFrame (`'country'` plus `'gdp_2020'`, `'gdp_2021'`, `'pop_2020'`, `'pop_2021'`) into long format with `pd.wide_to_long`, one row per (country, year).
The function must:
- Call `pd.wide_to_long` with `stubnames=['gdp','pop']`, `i='country'`, `j='year'`, `sep='_'`, `suffix='\d+'`.
- Call `.reset_index()` on the `('country', 'year')` MultiIndex.
- Return columns exactly `['country', 'year', 'gdp', 'pop']`.
Input:
```text
country gdp_2020 gdp_2021 pop_2020 pop_2021
0 US 21 23 331 332
1 UK 3 3 67 67
```
Output:
```text
country year gdp pop
0 US 2020 21 331
1 UK 2020 3 67
2 US 2021 23 332
3 UK 2021 3 67
```
```hint Look at the intermediate frame
`wide_to_long` returns its result indexed by the `i` and `j` columns. Print that frame and compare its index, columns and row order with the required output before deciding what else the function has to do.
```
### What a Strong Answer Covers
- Explains how `stubnames`, `sep` and `suffix` split a column such as `gdp_2020` into the stub `gdp` and the year 2020.
- Turns the `(country, year)` MultiIndex back into columns and returns exactly `country`, `year`, `gdp`, `pop` in that order.
- Explains the dtype of `year` and the row order of the result.
- Covers what `wide_to_long` needs from the `i` column and what happens when a stub has no column for some year.
### Follow-up Questions
- Why is `year` an integer rather than a string?
- How would you handle stubs with inconsistent separators or no separator?
- What happens if `country` is not unique, or if the frame has `pop_2022` but no `gdp_2022`?
Overview: Reshape a wide panel of yearly GDP and population columns into one row per country and year with pandas wide_to_long. It tests how stub names, separators and suffixes are parsed, MultiIndex handling, row order, and the dtype of the extracted year.