Class Balance Summary
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `class_balance(df, target)`. Given a pandas DataFrame with an integer 0/1 column named by `target`, return one row per distinct class with columns exactly `['class', 'n', 'pct', 'is_minority']`.
The result must meet these requirements:
- `class` is the target value (`int64`). `n` is the row count (`int64`).
- `pct` is the class's share of all rows as an unrounded proportion in [0, 1] (`float64`), and the column sums to 1.0.
- `is_minority` is `bool`, True only for the single least-frequent class.
- Rows are sorted by `n` descending, then `class` ascending, followed by `reset_index(drop=True)`.
- The function is graded with `assert_frame_equal`, so names, order, dtypes and index must all match.
```python
# df has 100 rows: 80 of class 0, 20 of class 1
class_balance(df, "target")
# class n pct is_minority
# 0 0 80 0.8 False
# 1 1 20 0.2 True
```
```hint Dtypes and the minority flag
One tally gives the count per class, but check the dtypes of its index and values against what the grader expects. Compute `is_minority` in a way that does not depend on where a row ends up after sorting.
```
### Constraints & Assumptions
- `target` holds the integers 0 and 1 with no missing values.
- In the graded data the least-frequent class is unique, so exactly one row has `is_minority` True.
### What a Strong Answer Covers
- Counts rows per class in one pass and keeps the class labels as `int64`
- Computes `pct` against the total row count without rounding
- Flags the minority from the minimum count, independent of sort position
- Produces the exact column order, sort order and a fresh 0-based index
- Names edge cases such as a single-class target and a tie for the minimum
### Follow-up Questions
- How would you handle a tie for the least-frequent class?
- How would you generalize this to multiclass targets?
- What would you change if the target column could contain missing values?
Overview: Write a pandas function that summarizes class balance for a binary target, with row counts, unrounded shares and a flag for the least-frequent class. It tests value counting, exact dtypes and sort order under a strict frame comparison, and edge cases such as ties.