Normalize DataFrame Column Labels to snake_case in Pandas
Quick Overview
Write a pandas function that returns a copy of a DataFrame with its column labels stripped, lowercased and converted to snake_case, leaving the values and row index unchanged. It tests the Index string accessor, avoiding in-place mutation, and edge cases such as colliding or non-string labels.
Normalize DataFrame Column Labels to snake_case in Pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `clean_columns(df: pd.DataFrame) -> pd.DataFrame`. Column labels may have leading or trailing spaces, uppercase letters and internal single spaces. Return a new DataFrame with snake_case column labels.
The function must meet these requirements:
- Apply `df.columns.str.strip().str.lower().str.replace(' ', '_')`.
- Do not mutate the input in place.
- Row values and the row index must be identical to the input.
For example:
```text
cols in: ['First Name', ' Last Name', 'Email Address']
cols out: ['first_name', 'last_name', 'email_address']
```
```hint Work on the labels only
The column labels are an Index with its own string accessor. Think about how to give new labels to a frame that is not the caller's, and what that costs.
```
### What a Strong Answer Covers
- How the label transform is applied to the column Index as a whole, and why the order of the steps matters.
- How the function returns a new frame and leaves the caller's frame unchanged.
- Why the values and the row index come through untouched.
- Inputs that break the simple chain, such as non-string labels or labels that collide after cleaning.
### Follow-up Questions
- How would you handle repeated internal spaces, tabs, hyphens or punctuation in the labels?
- How would you convert camelCase labels such as `firstName` into snake_case?
- What happens if two labels become the same after cleaning, and how would you deal with it?
- What happens if some column labels are integers?
Overview: Write a pandas function that returns a copy of a DataFrame with its column labels stripped, lowercased and converted to snake_case, leaving the values and row index unchanged. It tests the Index string accessor, avoiding in-place mutation, and edge cases such as colliding or non-string labels.
Implement clean_columns(df: pd.DataFrame) -> pd.DataFrame. Column labels may have leading or trailing spaces, uppercase letters and internal single spaces. Return a new DataFrame with snake_case column labels.