Drop Sparse Pandas Columns Below a Non-Null Count Threshold
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def drop_sparse_columns(df: pd.DataFrame, min_non_null: int) -> pd.DataFrame`. Drop every column with fewer than `min_non_null` non-missing values and return a new DataFrame.
Requirements:
- Surviving columns keep their original order, index, and dtypes.
- Do not modify `df` in place.
For example:
```python
df = pd.DataFrame({
'a': [1, 2, 3, 4], # 4 non-null
'b': [1, None, None, 4], # 2 non-null
'c': [None, None, 3, 4], # 2 non-null
})
drop_sparse_columns(df, min_non_null=3)
# keeps only column 'a'
```
```hint One number per column
Reduce each column to a single count of the values that are present, then compare it with `min_non_null`. Decide which side of the cut a column with exactly `min_non_null` values falls on.
```
### What a Strong Answer Covers
- Applying the rule to columns, with "at least `min_non_null`" semantics at the boundary.
- What pandas counts as missing when it counts present values, and which placeholders it treats as present.
- How column order, the index and dtypes are preserved, and why `df` is left unchanged.
- The edge cases: a threshold of 0 or below, a threshold larger than the number of rows, and an empty frame.
### Follow-up Questions
- How does the non-null count treat object columns compared with numeric columns, and what happens to placeholders such as empty strings or `0`?
- How would you drop by a fraction of non-null values instead of a fixed count?
- What should the function return when `min_non_null` is larger than the number of rows?
Overview: Write a pandas function that drops every DataFrame column with fewer than a given number of non-missing values, keeping column order, the index and dtypes. It tests column-wise missing-value counting, the threshold boundary, what pandas treats as missing, and how to turn the rule into a fraction safely.