Build a top-N plus Other frequency report from a pandas Series

Quick Overview

Write a pandas function that turns a Series into a frequency report with the top n levels and one Other row that holds the rest. It tests value_counts, deterministic tie-breaking, percentages over the non-null total, NaN handling and exact dtypes for assert_frame_equal.

Build a top-N plus Other frequency report from a pandas Series

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Implement `top_n_with_other(s: pd.Series, n: int = 3) -> pd.DataFrame`. It returns a frequency report for the values of `s`: the `n` most common levels, followed by one `'Other'` row that aggregates everything else. The result is a new summary table with at most `n + 1` rows, and its columns are `level` (object), `count` (int64) and `pct` (float64). The report must follow these rules: - The first rows are the top `n` levels, ordered by `count` descending and then by `level` ascending to break ties. - The final row is `'Other'` and holds the combined count of all remaining levels. It is always present and always last. When `s` has `n` or fewer distinct levels, that row has count 0 and pct 0.0. - `pct` is the row's count divided by the total number of non-null values in `s`, times 100. The `'Other'` row counts toward that total. - NaN values are excluded from every count. - The result has a fresh `RangeIndex`, and the dtypes must match exactly, because the grader compares frames with `assert_frame_equal`. Example: ```python s = pd.Series(['a', 'a', 'a', 'b', 'b', 'c', 'd', np.nan]) top_n_with_other(s, n=2) # level count pct # 0 a 3 42.857143 # 1 b 2 28.571429 # 2 Other 2 28.571429 # c + d, NaN excluded ``` There are 7 non-null values, so `a` gets 3 out of 7 and the `'Other'` row (c and d together) gets 2 out of 7. ```hint Where the details bite `assert_frame_equal` checks the index and every dtype, so it is easier to build the result from fresh, explicitly typed columns than to patch the output of `value_counts()`. Also check which total each percentage is divided by. ``` ### Constraints & Assumptions - `s` holds hashable values that can be compared with each other, so the ascending tie-break on `level` is defined. - `s` may contain NaN or `None`, and it may be empty or entirely missing. - `n` is a non-negative integer. ### What a Strong Answer Covers - Counting with NaN excluded and ordering by count descending, then level ascending, so the top rows are deterministic under ties. - Computing the `'Other'` count as the leftover mass, including the zero case when there are `n` or fewer levels. - Using the full non-null total as the pct denominator, with a guard for a total of 0. - Returning exact dtypes (`object`, `int64`, `float64`) on a fresh `RangeIndex`. ### Follow-up Questions - How would you support rounding `pct` without breaking `assert_frame_equal`? - What should the function return when the Series is empty or all-NaN? - What goes wrong if one of the real levels in `s` is the string `'Other'`, and how would you handle it? - How would you produce the same report for each group of a grouped DataFrame?

Overview: Write a pandas function that turns a Series into a frequency report with the top n levels and one Other row that holds the rest. It tests value_counts, deterministic tie-breaking, percentages over the non-null total, NaN handling and exact dtypes for assert_frame_equal.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement top_n_with_other(s: pd.Series, n: int = 3) -> pd.DataFrame. It returns a frequency report for the values of s: the n most common levels, followed by one 'Other' row that aggregates everything else. The result is a new summary table with at most n + 1 rows, and its columns are level (object), count (int64) and pct (float64).

The report must follow these rules:

  • The first rows are the top n levels, ordered by count descending and then by level ascending to break ties.
  • The final row is 'Other' and holds the combined count of all remaining levels. It is always present and always last. When s has n or fewer distinct levels, that row has count 0 and pct 0.0.
  • pct is the row's count divided by the total number of non-null values in s , times 100. The 'Other' row counts toward that total.
  • NaN values are excluded from every count.
  • The result has a fresh RangeIndex , and the dtypes must match exactly, because the grader compares frames with assert_frame_equal .

Example:

s = pd.Series(['a', 'a', 'a', 'b', 'b', 'c', 'd', np.nan])
top_n_with_other(s, n=2)
#    level  count        pct
# 0      a      3  42.857143
# 1      b      2  28.571429
# 2  Other      2  28.571429   # c + d, NaN excluded

There are 7 non-null values, so a gets 3 out of 7 and the 'Other' row (c and d together) gets 2 out of 7.

Constraints & Assumptions

  • s holds hashable values that can be compared with each other, so the ascending tie-break on level is defined.
  • s may contain NaN or None , and it may be empty or entirely missing.
  • n is a non-negative integer.

What a Strong Answer Covers Guidance

  • Counting with NaN excluded and ordering by count descending, then level ascending, so the top rows are deterministic under ties.
  • Computing the 'Other' count as the leftover mass, including the zero case when there are n or fewer levels.
  • Using the full non-null total as the pct denominator, with a guard for a total of 0.
  • Returning exact dtypes ( object , int64 , float64 ) on a fresh RangeIndex .

Follow-up Questions Guidance

  • How would you support rounding pct without breaking assert_frame_equal ?
  • What should the function return when the Series is empty or all-NaN?
  • What goes wrong if one of the real levels in s is the string 'Other' , and how would you handle it?
  • How would you produce the same report for each group of a grouped DataFrame?