Per-Column Dtype Schema Check for a pandas DataFrame
Quick Overview
Write a pandas function that checks each column's dtype against a fixed schema and returns a named boolean Series in schema order. It tests careful Series construction, the string forms of pandas dtypes, and when an exact match should give way to type-family helpers.
Per-Column Dtype Schema Check for a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def dtype_ok(df: pd.DataFrame) -> pd.Series` to validate a frame against this hard-coded schema. Return a boolean Series indicating, per column, whether the actual dtype matches the expected one.
```python
{'id': 'int64', 'name': 'object', 'signup': 'datetime64[ns]'}
```
The result must meet these requirements:
- Series dtype is `bool` (not object), named `'dtype_ok'`.
- Index is `['id', 'name', 'signup']` in schema order.
- Value is `True` exactly when `str(df[col].dtype) == expected`.
Example:
```python
# df: id -> object (wrong), name -> object, signup -> datetime64[ns]
dtype_ok(df)
# id False
# name True
# signup True
# Name: dtype_ok, dtype: bool
```
```hint What drives the loop
Decide what you iterate over. The order of the output index and the dtype of the output both depend on that choice and on how you build the Series.
```
### Constraints & Assumptions
- The input always has exactly the three schema columns, with no missing or extra columns.
### What a Strong Answer Covers
- Produces the index in schema order, independent of the column order in `df`.
- Guarantees the `bool` dtype and the `'dtype_ok'` name.
- Compares the string form of each dtype and explains why that matches the schema literals.
- Names dtypes that are equivalent in practice but fail an exact string match.
### Follow-up Questions
- How would you handle a column missing entirely from `df`?
- Why is exact string matching brittle, and when might `pd.api.types` be better?
- How would you also report columns in `df` that the schema does not list?
Overview: Write a pandas function that checks each column's dtype against a fixed schema and returns a named boolean Series in schema order. It tests careful Series construction, the string forms of pandas dtypes, and when an exact match should give way to type-family helpers.
Implement def dtype_ok(df: pd.DataFrame) -> pd.Series to validate a frame against this hard-coded schema. Return a boolean Series indicating, per column, whether the actual dtype matches the expected one.