Memory-Optimized pandas DataFrame Copy with Downcasting and Categories

Quick Overview

Write a pandas function that returns a smaller copy of a DataFrame by downcasting int64 and float64 columns and turning low-cardinality object columns into categories. It tests exact dtype checks, a strict cardinality threshold, avoiding mutation of the input, and what downcasting does to values.

Memory-Optimized pandas DataFrame Copy with Downcasting and Categories

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Implement `shrink_memory(df: pd.DataFrame) -> pd.DataFrame` returning a memory-optimized copy of `df` by downcasting numeric columns and converting low-cardinality object columns to categories. Do not mutate the input. Requirements: - Apply in order: `int64` columns via `pd.to_numeric(col, downcast='integer')`, then `float64` via `pd.to_numeric(col, downcast='float')`, then category conversion. - Convert an `object` column with `astype('category')` only if `nunique() / len(df) < 0.5` (strictly less). - Leave other `object` columns (ratio of `0.5` or more) and all other dtypes untouched. - Preserve column order and the index exactly. - The result must match the reference built by these rules under `assert_frame_equal`. Example: ```python df = pd.DataFrame({ "id": [1, 2, 3, 4], "score": [1.0, 2.5, 3.0, 4.0], "grade": ["A", "A", "B", "A"], "city": ["NY", "NY", "LA", "NY"], }) out = shrink_memory(df) # out['id'].dtype == int8, out['score'].dtype == float32 ``` ```hint Match the dtypes exactly The rules name exact dtypes. A broad check such as "any integer type" also catches `int32` or `uint8` columns, which must stay untouched. ``` ```hint Check the boundary Before writing the comparison, compute the cardinality ratio by hand for the two text columns in the example. ``` ### Constraints & Assumptions - Assume a non-empty frame, so `len(df)` is at least 1. ### What a Strong Answer Covers - Working on a copy so the input is unchanged, with column order and index preserved. - Dtype checks that touch only `int64`, `float64` and `object` columns. - The strict `< 0.5` threshold, including what it does at exactly `0.5` and how `nunique()` counts missing values. - What downcasting does to the values: which integer subtype is chosen and when a float column can or cannot move to `float32`. ### Follow-up Questions - How much memory does `category` actually save, and when can it backfire? - How would you handle a `float64` column containing `NaN` values during downcasting? What about integer data with missing values? - How would you measure the memory saved, so the number includes the strings inside object columns?

Overview: Write a pandas function that returns a smaller copy of a DataFrame by downcasting int64 and float64 columns and turning low-cardinality object columns into categories. It tests exact dtype checks, a strict cardinality threshold, avoiding mutation of the input, and what downcasting does to values.

General logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement shrink_memory(df: pd.DataFrame) -> pd.DataFrame returning a memory-optimized copy of df by downcasting numeric columns and converting low-cardinality object columns to categories. Do not mutate the input.

Requirements:

  • Apply in order: int64 columns via pd.to_numeric(col, downcast='integer') , then float64 via pd.to_numeric(col, downcast='float') , then category conversion.
  • Convert an object column with astype('category') only if nunique() / len(df) < 0.5 (strictly less).
  • Leave other object columns (ratio of 0.5 or more) and all other dtypes untouched.
  • Preserve column order and the index exactly.
  • The result must match the reference built by these rules under assert_frame_equal .

Example:

df = pd.DataFrame({
    "id": [1, 2, 3, 4],
    "score": [1.0, 2.5, 3.0, 4.0],
    "grade": ["A", "A", "B", "A"],
    "city": ["NY", "NY", "LA", "NY"],
})
out = shrink_memory(df)
# out['id'].dtype == int8, out['score'].dtype == float32

Constraints & Assumptions

  • Assume a non-empty frame, so len(df) is at least 1.

What a Strong Answer Covers Guidance

  • Working on a copy so the input is unchanged, with column order and index preserved.
  • Dtype checks that touch only int64 , float64 and object columns.
  • The strict < 0.5 threshold, including what it does at exactly 0.5 and how nunique() counts missing values.
  • What downcasting does to the values: which integer subtype is chosen and when a float column can or cannot move to float32 .

Follow-up Questions Guidance

  • How much memory does category actually save, and when can it backfire?
  • How would you handle a float64 column containing NaN values during downcasting? What about integer data with missing values?
  • How would you measure the memory saved, so the number includes the strings inside object columns?