Find constant columns in a pandas DataFrame, counting NaN as a value
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def constant_columns(df: pd.DataFrame) -> list[str]` that returns the names of columns whose distinct-value count, counting nulls as a value, is `<= 1` (that is, `df[c].nunique(dropna=False) <= 1`).
Requirements:
- Use `nunique(dropna=False)` so nulls count as a distinct value.
- An all-NaN column and an all-`'US'` column are both constant.
- `['a', 'a', NaN]` is not constant (two distinct values).
- Return a plain `list` of strings sorted ascending, or `[]` when no column is constant.
Example:
```python
df = pd.DataFrame({
'same_int': [1, 1, 1, 1, 1, 1],
'same_str': ['US'] * 6,
'all_nan': [np.nan] * 6,
'mixed': ['a', 'a', np.nan, 'a', 'a', 'a'],
'x': [1, 2, 3, 4, 5, 6],
})
constant_columns(df) # ['all_nan', 'same_int', 'same_str']
```
```hint Watch the nulls
Check what pandas' distinct count does with NaN by default, and how that changes the answer for the `all_nan` and `mixed` columns.
```
### What a Strong Answer Covers
- Counting nulls as their own value so an all-NaN column is constant and a value-plus-NaN column is not
- Why the threshold is `<= 1` and what that means for a DataFrame with zero rows
- Returning column names as strings in sorted order, including when the names are not strings
- Time and space cost of the scan
### Follow-up Questions
- How would you flag near-constant columns, such as one value covering 99% of rows?
- How would you run the same check in SQL or on a table too large to load into memory?
- Should constant columns always be dropped before modeling?
Overview: Write a pandas function that returns the sorted names of columns holding at most one distinct value, where nulls count as a value. It tests how distinct counts treat NaN, edge cases such as empty frames and non-string column names, and basic data-quality checks during exploratory analysis.