Classify pandas DataFrame columns as boolean, datetime, numeric or categorical
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `classify_columns(df: pd.DataFrame) -> pd.Series`, which labels each column of a DataFrame by its dtype. Return a Series indexed by column name.
Requirements:
- Each value is exactly one of `'boolean'`, `'datetime'`, `'numeric'` or `'categorical'`.
- Use `'boolean'` for `bool` dtype. Test for it before numeric, because pandas' numeric check also returns True for bool columns.
- Use `'datetime'` for any `datetime64` dtype and `'numeric'` for the other int and float dtypes.
- Use `'categorical'` for object, string and category dtypes.
- Keep the original column order (do not sort), and return the Series with `name=None` and `dtype=object`.
Example:
```python
df = pd.DataFrame({
"age": [34, 51],
"score": [0.82, 0.67],
"active": [True, False],
"signup_at": pd.to_datetime(["2024-01-05", "2024-03-17"]),
"city": ["Austin", "Denver"],
"tier": pd.Categorical(["gold", "silver"]),
})
# columns: int64, float64, bool, datetime64[ns], object, category
classify_columns(df)
# age numeric
# score numeric
# active boolean
# signup_at datetime
# city categorical
# tier categorical
# dtype: object
```
```hint Which checks overlap
Look at the helpers in `pandas.api.types`. Work out which of them can return True for the same column, and order your checks so every column reaches the right one first.
```
### What a Strong Answer Covers
- Checking bool before numeric, with the reason a bool column passes a numeric check
- Treating every `datetime64` variant, including timezone-aware ones, as datetime
- Keeping the original column order and returning a Series with `name=None` and object dtype
- Dtype checks that work for numpy dtypes and pandas extension dtypes alike
- Edge cases the four rules do not settle, such as timedelta columns, a category of booleans, or duplicate column names
### Follow-up Questions
- How would you distinguish continuous from discrete numeric columns?
- What changes for nullable dtypes such as `Int64`, `boolean` and `string`?
- An object column holds values like `'12'` and `'7.5'`. How would you detect that it is really numeric, and what about dates stored as text?
Overview: Write a pandas function that labels every DataFrame column as boolean, datetime, numeric or categorical from its dtype while keeping the original column order. It tests the pandas.api.types dtype checks, the order they run in, and how nullable extension dtypes behave.