← All Python interview questions
Shrink a DataFrame's memory footprint
MediumPandas — CleaningAmazonWalmart
A 40-million-row extract will not fit in memory with default dtypes.
Write optimise(df) that returns a copy where integer columns are downcast to the smallest safe integer type, float columns to the smallest safe float type, and object columns with fewer than 50% unique values become category.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
import numpy as np
wide = pd.DataFrame({
"id": np.arange(1, 9, dtype="int64"),
"score": np.array([1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5], dtype="float64"),
"city": ["Mumbai", "Delhi", "Mumbai", "Delhi", "Mumbai", "Delhi", "Mumbai", "Delhi"],
"note": ["a", "b", "c", "d", "e", "f", "g", "h"],
})- Step 1: `pd.to_numeric(..., downcast='integer')` picks the smallest integer type that still holds every value — int8 here instead of int64, an 8x saving.
- Step 2: Float downcasting to float32 halves the memory but also halves the precision; that trade is fine for scores, not for money.
- Step 3: The 50% cardinality rule is the standard heuristic: `category` wins big on repeated strings and loses on near-unique ones like free-text notes.
- Step 4: Working on a copy keeps the original frame available if a downcast turns out to be too aggressive.
def optimise(df):
out = df.copy()
for col in out.columns:
s = out[col]
if pd.api.types.is_integer_dtype(s):
out[col] = pd.to_numeric(s, downcast="integer")
elif pd.api.types.is_float_dtype(s):
out[col] = pd.to_numeric(s, downcast="float")
elif pd.api.types.is_object_dtype(s) or pd.api.types.is_string_dtype(s):
if len(s) and s.nunique() / len(s) < 0.5:
out[col] = s.astype("category")
return outLearn the concept first
Stuck on Pandas — Cleaning? These free Python lessons teach it step by step.
More Pandas — Cleaning questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program