Transpose a city-keyed pandas DataFrame so metrics become rows and cities become columns
Quick Overview
Write a pandas function that transposes a small numeric table keyed by city, so metric names become rows and cities become columns. It tests index handling, how axis names move during a transpose, and what transposing does to column dtypes.
Transpose a city-keyed pandas DataFrame so metrics become rows and cities become columns
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `transpose_table(df)` that returns the transpose of a small numeric DataFrame keyed by city, so metric names become rows and city labels become columns.
```python
import pandas as pd
def transpose_table(df: pd.DataFrame) -> pd.DataFrame:
...
```
Requirements:
- `city` may arrive as a regular column or already as the index. If it is a column, use it as the row labels before transposing.
- The result's columns axis is named `'city'`.
- Return the transposed frame as it is: do not reset the index or rename any axes.
Example:
```python
df = pd.DataFrame({
'city': ['NYC', 'LA'],
'temp': [30, 75],
'pop': [8, 4],
})
transpose_table(df)
# city NYC LA
# temp 30 75
# pop 8 4
# columns axis name: 'city'
```
```hint Follow the labels
Look at which axis carries the name `'city'` before the transpose and where that name goes afterwards. Then check what your code does when `city` is already the index.
```
### Constraints & Assumptions
- The frame is small: a handful of cities and metrics.
- Every column other than `city` is numeric.
- When `city` is already the index, that index is named `'city'`.
### What a Strong Answer Covers
- Handling both input shapes, with `city` as a column or as the index.
- A result with metric names as rows and cities as columns, in the input order.
- Where the `'city'` axis name comes from, without renaming anything by hand.
- What transposing does to the column dtypes.
### Follow-up Questions
- Why does the columns axis end up named `'city'` after transposing?
- What happens to the dtypes if one metric is an integer and another a float, or if a text column slips in?
- What changes if two rows have the same city?
Overview: Write a pandas function that transposes a small numeric table keyed by city, so metric names become rows and cities become columns. It tests index handling, how axis names move during a transpose, and what transposing does to column dtypes.
Write transpose_table(df) that returns the transpose of a small numeric DataFrame keyed by city, so metric names become rows and city labels become columns.
import pandas as pd
def transpose_table(df: pd.DataFrame) -> pd.DataFrame:
...
Requirements:
city
may arrive as a regular column or already as the index. If it is a column, use it as the row labels before transposing.
The result's columns axis is named
'city'
.
Return the transposed frame as it is: do not reset the index or rename any axes.