Python and Pandas for Data Analysis Questions
Programmatic data manipulation and analysis in Python and R. Covers pandas transformations, joins and reshaping, aggregation, working with PySpark for larger data, and using R for statistical analysis. Emphasizes clean, reproducible analytical code.
You have two DataFrames df_a and df_b, both indexed by the same MultiIndex ['region','store_id'], with some overlapping columns. Explain how to perform a left join of df_a to df_b while preserving that MultiIndex, and what can go wrong if the index level names or dtypes differ between the two frames.
Sample Answer
Direct answer: When df_a and df_b already share an identical MultiIndex on ['region', 'store_id'], df_a.join(df_b, how='left') performs an index-aligned left join and keeps the MultiIndex intact with no extra steps. The failure mode to watch for is that the join matches on index labels, so if the level names or the level dtypes differ between the two frames, pandas either raises or (worse) silently returns all-null matches instead of the join you intended.
Structured elaboration / approach, worked end to end (verified, pandas 3.0.3):
Start from two frames that already share the MultiIndex on ['region', 'store_id'] with matching dtypes:
import pandas as pd
idx_a = pd.MultiIndex.from_tuples([('east', 101), ('east', 102), ('west', 201)],
names=['region', 'store_id'])
df_a = pd.DataFrame({'sales': [100, 200, 300]}, index=idx_a)
idx_b_ok = pd.MultiIndex.from_tuples([('east', 101), ('west', 201)],
names=['region', 'store_id'])
df_b = pd.DataFrame({'inventory': [10, 20]}, index=idx_b_ok)
result = df_a.join(df_b, how='left', lsuffix='_a', rsuffix='_b')
print(result)
Verified output:
sales inventory
region store_id
east 101 100 10.0
102 200 NaN
west 201 300 20.0
join aligns on the index, so as long as both frames have a MultiIndex with matching level names (in the same order) and matching level dtypes, this is a direct, memory-light left join that never leaves the index representation.
Now the pitfall, in the same session: store_id as int64 on the left, str on the right (a very ordinary way for this to happen: one frame loaded from a database with a typed column, the other from a CSV or an API response):
idx_b_bad = pd.MultiIndex.from_tuples([('east', '101'), ('west', '201')],
names=['region', 'store_id'])
df_b_bad = pd.DataFrame({'inventory': [10, 20]}, index=idx_b_bad)
print(df_a.join(df_b_bad, how='left'))
Verified output:
sales inventory
region store_id
east 101 100 NaN
102 200 NaN
west 201 300 NaN
This is the dangerous case: join does not error, it silently returns NaN (not-a-number, pandas' missing-value marker) for every row because int64(101) != str('101') as index labels. There is no warning.
Fix: reset to columns, normalize the dtype explicitly, merge on columns, restore the MultiIndex:
a = df_a.reset_index()
b = df_b_bad.reset_index()
a['store_id'] = a['store_id'].astype(int)
b['store_id'] = b['store_id'].astype(int)
merged = a.merge(b, on=['region', 'store_id'], how='left', suffixes=('_a', '_b'))
fixed_result = merged.set_index(['region', 'store_id']).sort_index()
print(fixed_result)
Verified output: identical to the first, correct join shown above, every row lines up once both sides carry the same store_id dtype.
Key points
joinmatches by index label equality across every level, so level names also matter: ifdf_b's levels are named['area', 'store_id']instead of['region', 'store_id'],joinon the index will not align the way you expect, preferreset_index()+merge(..., on=[...])with explicit column names whenever you are not certain both frames were built the same way.- Overlapping non-key columns need
lsuffix/rsuffix(for.join) orsuffixes=(for.merge), otherwise pandas raisesValueError: columns overlap but no suffix specified. - A left join keeps every row of
df_a; ifdf_bhas duplicate index entries for a key, that row multiplies (verified: one left row against two duplicate right-side rows produces two output rows), so dedupe or pre-aggregatedf_bon the key first if you expect one-to-one.
Complexity: With both frames already carrying an aligned MultiIndex, .join is close to O(n log n) (an index-aligned merge using the underlying hash/sort machinery) and does not need to materialize the index columns, so it is both the fastest and the lowest-memory option when the indexes are already trustworthy. The reset_index → merge → set_index path does the same asymptotic work but pays for two extra full-frame copies (the reset and the final set_index), which matters at large row counts.
Edge cases:
- Empty
df_b: a left join against an empty frame just returnsdf_a's rows with all the right-hand columns asNaN, no error. - All levels present but wrong dtype (shown above): silent all-
NaNresult, the single most dangerous failure because nothing crashes. - Duplicate keys in
df_b: row-count multiplication on the matching keys, verified above. - Unsorted index on either side: correctness is unaffected, but you may see a
PerformanceWarningabout indexing past lexsort depth;sort_index()first if you will also be slicing the result.
Design a robust solution to align and resample irregular event time-series from multiple users across different timezones. Requirements: align to hourly UTC buckets, handle DST transitions correctly, forward-fill missing values per user up to a 6-hour limit, and produce a consistent index for downstream ML features. Outline steps and show pandas code for timezone-aware resampling and per-user forward-fill.
Sample Answer
Direct answer: Localize every event to its own user's timezone with pandas' dst-aware tz_localize (never convert a naive timestamp to UTC by a fixed offset), convert everything to a single hourly UTC index, reindex every user onto that same shared index so all users produce aligned feature rows, and forward-fill with an explicit limit=6 so a stale value never silently propagates further than 6 hours. The subtlety that breaks most first attempts is daylight saving time (DST): a naive "just localize and convert" step will either crash or silently mis-time events unless the two DST edge cases, a nonexistent local time (spring forward) and an ambiguous local time (fall back), are handled explicitly rather than left to a default.
Structured elaboration: approach
- Normalize every event's naive local timestamp to UTC by localizing with that row's own IANA timezone (e.g.
"America/Los_Angeles"), never by a fixed numeric offset, since the offset itself changes across a DST boundary. - Build one shared hourly UTC index spanning the data's time range.
- Group by user,
reindexeach user's series onto that shared index (this is what "align to hourly UTC buckets" means in practice), and forward-fill withlimit=6. - Return a consistent
(user_id, event_time_utc)index so every downstream ML feature join lines up.
Worked example, localization step (verified, pandas 3.0.3), including the DST fix:
import pandas as pd
def to_utc(ts_series, tz_series):
out = []
for tz, grp_idx in tz_series.groupby(tz_series).groups.items():
sel = ts_series.loc[grp_idx]
# nonexistent='shift_forward' resolves the spring-forward gap deterministically.
# ambiguous='NaT' flags the fall-back hour instead of guessing, see the correction below.
localized = sel.dt.tz_localize(tz, ambiguous='NaT', nonexistent='shift_forward')
out.append(localized.dt.tz_convert('UTC'))
return pd.concat(out).sort_index()
Self-initiated correction, with evidence: a natural first draft uses ambiguous='infer', which asks pandas to deduce the fall-back DST transition from repeated timestamps in the series. Tested directly against a single-row series landing exactly on the fall-back-ambiguous hour in America/Los_Angeles (2023-11-05 01:30:00, which occurs twice that day):
try:
pd.Series(pd.to_datetime(['2023-11-05 01:30:00'])).dt.tz_localize(
'America/Los_Angeles', ambiguous='infer', nonexistent='shift_forward')
except ValueError as e:
# expected: a single-row series has no repeated timestamp for pandas to infer from
print(f'raises as expected: ValueError: {e}')
ambiguous='infer' raises unless the series contains the actual repeated-time pattern pandas needs to detect the transition, which a typical per-user event stream will not reliably have. That means the exact DST edge case this question asks you to handle correctly is the one input that crashes the naive version. ambiguous='NaT' instead marks that single ambiguous timestamp as NaT (verified: it does not raise, and the ambiguous row's converted timestamp comes back as NaT while every unambiguous row converts correctly), so the pipeline degrades gracefully and the ambiguous event is explicitly flagged for review rather than either crashing the whole run or silently guessing which of the two possible UTC times is correct.
Resample and per-user forward-fill (verified, pandas 3.0.3): taking df as the already-UTC-indexed frame produced by the step above (here a small concrete fixture, two users, gaps left deliberately so the fill limit is visible):
df = pd.DataFrame({
'user_id': ['u1', 'u1', 'u1', 'u2', 'u2'],
'value': [1.0, 2.0, 3.0, 10.0, 20.0],
}, index=pd.to_datetime([
'2023-06-01 15:00:00', '2023-06-01 16:15:00', '2023-06-01 19:00:00',
'2023-06-01 08:00:00', '2023-06-01 08:30:00',
], utc=True)).sort_index()
df.index.name = 'event_time_utc'
start = df.index.min().floor('h') # pandas 3.0 requires lowercase 'h'; uppercase 'H' now raises ValueError
end = df.index.max().ceil('h')
global_hours = pd.date_range(start, end, freq='h', tz='UTC')
def resample_and_ffill(g):
# g.name is the group key (user_id); as of pandas 3.0, groupby.apply excludes
# the grouping column from g by default (include_groups now defaults to False),
# so read the user id from g.name rather than g['user_id'].
reindexed = g.reindex(global_hours)
reindexed['value'] = reindexed['value'].ffill(limit=6)
reindexed['user_id'] = g.name
return reindexed
out = df.groupby('user_id', group_keys=False)[['value']].apply(resample_and_ffill)
Verified output: u1's hourly buckets are NaN (not-a-number, pandas' missing-value marker) from 08:00 through 14:00 (no data yet), 1.0 from 15:00 through 18:00 (the 15:00 reading forward-filled within the 6-hour limit), then 3.0 at 19:00 (a real reading); u2's buckets are 10.0 from 08:00 through 14:00 (forward-filled to the limit) then NaN from 15:00 onward (the fill limit is exhausted and no later reading exists). This confirms both the alignment onto a single shared hourly grid across users and the 6-hour forward-fill cap working as intended.
Second self-initiated correction, with evidence: the natural first draft writes freq='H'. Under pandas 3.0.3 this raises ValueError: Invalid frequency: H ... Did you mean h?, the uppercase hour alias was removed; freq='h' is required. Also verified: df.groupby('user_id').apply(f) where f reads g['user_id'] now raises KeyError: 'user_id', because pandas 3.0 defaults include_groups=False and excludes the grouping column from the frame passed into the function. Reading the group key from g.name (shown above) sidesteps this cleanly and needs no extra parameter.
Key points
- Convert to UTC per-row using each user's own timezone; converting first and localizing later, or using a single fixed offset for all users, silently produces wrong hour buckets for any user not in that one timezone.
reindexonto a sharedglobal_hoursindex (not a per-user resample) is what actually produces a consistent index across users for downstream ML feature joins.ffill(limit=6)caps how far a stale value can propagate; without the limit, a user who goes quiet for days would have their last real value silently repeated as if it were fresh for the entire gap.
Complexity: localization and UTC conversion is O(n) in the number of events. Building global_hours and reindexing each user onto it is O(h) per user where h is the number of hourly buckets in the window, so total cost is O(n + u*h) for u users, which is the real scaling risk: a long time window with a fixed hourly grid multiplies by every user even for users with very few actual events. ffill(limit=6) is O(h) per user, a single forward pass.
Edge cases
- User with zero events in the window:
reindexproduces an all-NaNrow for every bucket; decide explicitly whether to drop that user or keep the all-NaNrows as a signal to a downstream model. - Sparse users:
ffill(limit=6)still leaves long stretches ofNaNfor a user who reports rarely; add an explicit "hours since last real observation" or "was imputed" indicator column so a downstream model can distinguish a genuine reading from a forward-filled one. - DST fall-back (ambiguous local time): now flagged as
NaTrather than crashing or guessing, shown above. - DST spring-forward (nonexistent local time): resolved deterministically by
nonexistent='shift_forward', which shifts the invalid local time to the next valid instant. - Scale beyond a single machine: the same per-user timezone-conversion-then-hourly-reindex pattern generalizes to a distributed engine (e.g. Spark) once the row count no longer fits comfortably in memory; the logic does not change, only the execution engine does.
You must join customer records from two sources where the same person's name and address are spelled slightly differently between systems (typos, abbreviations, formatting differences), so an exact-key join misses real matches. Propose an approach to link these records that scales beyond a handful of rows, and discuss how you would guard against false matches and validate the results before trusting them downstream.
Sample Answer
Direct answer: Reduce the number of comparisons with cheap blocking (exact-match on a coarse key like zip code) so you never compare every record against every other record, then compute an approximate string-similarity score on the fields that actually vary (name, address) within each block, and use two thresholds instead of one: an auto-accept threshold for high-confidence matches and a lower "send to human review" band for everything else. Validate on a labeled sample before trusting any threshold in production.
Structured elaboration: approach
- Block on a cheap exact key that correlates with true matches (zip code, or city + zip) to cut comparisons from O(n * m) to the sum of O(n_b * m_b) over much smaller blocks.
- Score each candidate pair within a block using a token-based fuzzy string metric (handles reordering, abbreviations, and minor typos better than edit distance alone), on both name and address, combined into one weighted score.
- Threshold in two tiers: auto-link above a high threshold, route a middle band to human review, and treat everything below the review floor as a non-match.
- Validate on a labeled sample before trusting the thresholds, and keep auditing a random slice of auto-matches after launch.
Worked example (verified, pandas 3.0.3, rapidfuzz 3.14.5):
import pandas as pd
from rapidfuzz import fuzz
left_df = pd.DataFrame({
'customer_id': [1, 2, 3],
'name': ['Jon Smith', 'Maria Garcia', 'Robert Lee'],
'address': ['123 Main St Apt 4', '55 Oak Ave', '9 Elm Rd'],
'zipcode': ['94110', '10001', '73301'],
})
right_df = pd.DataFrame({
'customer_id': [101, 102, 103],
'name': ['Jonathan Smith', 'Maria J Garcia', 'Rob Lee'],
'address': ['123 Main Street, Apt 4', '55 Oak Avenue', '10 Elm Rd'],
'zipcode': ['94110', '10001', '73301'],
})
def normalize_zip(z):
return str(z).strip()[:5] if pd.notna(z) else None
left_df['zip5'] = left_df['zipcode'].apply(normalize_zip)
right_df['zip5'] = right_df['zipcode'].apply(normalize_zip)
left_blocks = left_df.dropna(subset=['zip5'])
right_blocks = right_df.dropna(subset=['zip5'])
candidates = left_blocks.merge(right_blocks, on='zip5', suffixes=('_L', '_R'))
def combined_score(row, w_name=0.6, w_addr=0.4):
name_score = fuzz.token_set_ratio(row['name_L'], row['name_R']) # 0-100
addr_score = fuzz.token_set_ratio(row['address_L'], row['address_R'])
return w_name * name_score + w_addr * addr_score
candidates['score'] = candidates.apply(combined_score, axis=1)
AUTO_MATCH = 90
REVIEW_LOW = 70
matches_auto = candidates[candidates['score'] >= AUTO_MATCH]
matches_review = candidates[(candidates['score'] >= REVIEW_LOW) & (candidates['score'] < AUTO_MATCH)]
On this fixture the measured scores were 83.09, 94.78, and 83.70, giving 1 auto-match and 2 review-band matches at the thresholds above, no false positives and no missed true matches on this sample.
Complexity: without blocking, comparing every left row to every right row is O(N x M). Blocking on zip code reduces that to the sum over blocks of O(n_b x m_b), which is close to O(N + M) when blocks are small relative to the full datasets. Each pairwise score itself is O(k) in string length. The dominant cost at scale is usually the number of candidate pairs a block produces, not the scoring function, so a bad blocking key (one that's too coarse, producing huge blocks) can defeat the whole strategy even with a fast scorer.
Edge cases and how to guard against false matches
- Missing or malformed zip codes: records that fail the blocking key never get compared at all, and are silently dropped from the candidate set. Add a fallback block (city + first 3 digits of phone, or a phonetic key like Soundex on the last name) for rows where the primary block key is null, and track how many records never entered any block.
- Multiple candidate matches for one record: detect many-to-many matches explicitly rather than silently keeping only the highest score, they usually indicate either a genuinely ambiguous case or a data quality problem worth surfacing.
- International or inconsistently formatted addresses: general token-similarity scoring degrades quickly across address formats from different countries, a dedicated address-standardization step before scoring (parsing into number/street/unit/city/postal components) improves both blocking and scoring accuracy.
- Precision/recall trade-off: raising the auto-match threshold reduces false positives (bad merges) but pushes more true matches into the review queue or below it entirely; choose the operating point from a labeled validation sample and the real cost of a false merge versus a missed one, not a default like 90.
Trade-offs and pitfalls: validating before you trust it
- Never ship auto-linking on an unlabeled sample. Hand-label a few hundred candidate pairs across the score range, plot precision against threshold, and pick the auto-accept cutoff from that curve rather than a round number.
- Log every decision (score, which fields drove it, timestamp, source) so a bad auto-merge can be audited and reversed, treat linkage as a reversible operation, not a one-way write.
- Periodically re-sample already-auto-matched pairs for human spot-checking, upstream data quality drifts (new abbreviation conventions, a new source system) can silently degrade precision after launch even if nothing in your code changed.
- Weighting name higher than address (or vice versa) is a modeling choice, not a fact, validate it against your actual labeled data instead of assuming one field is inherently more reliable.
Explain and demonstrate with pandas code when to use groupby.transform vs groupby.apply or agg for feature engineering. Specifically compute for each user in an events DataFrame: (1) time since last event, (2) rolling count of events in the last 7 days, and (3) normalized 'value' by user mean using appropriate pandas methods that return aligned results suitable for assignment to new columns.
Sample Answer
Direct answer
Use .transform(...) whenever the result must come back aligned one-value-per-row for direct
column assignment (a time-since-last-event gap, a per-user normalization). Use
groupby(...).rolling(...) (not groupby().apply()) for a per-group time-windowed
calculation that also needs to come back aligned to one row per event; reserve .apply() for
group-level logic that genuinely does not fit transform's or agg's shape.
Structured elaboration
transformbroadcasts a per-group result back to every row of that group: the output is
always the same length as the input, so it can be assigned straight to a new column.aggcollapses each group to one summary row, the opposite shape oftransform.applyis the general escape hatch, for per-group logic that changes shape in a way
neithertransformnoraggcan express.- As of pandas 3.0,
groupby(...).apply(func)never passes the grouping column(s) intofunc
(theinclude_groups=Trueoption that used to restore the old, group-key-included behavior
was removed entirely; passing it now raisesValueError: include_groups=True is no longer allowed). For a windowed calculation like a rolling count, that is also a sign you are
reaching for the wrong tool: pandas' owngroupby(...).rolling(...)computes a per-group
rolling window directly, without anapplycall, and it never drops the group key from what
you can reference in the first place.
Worked example
import pandas as pd
# columns: user_id, event_time (datetime), value
df = pd.DataFrame({
'user_id': [1, 1, 1, 2, 2, 3],
'event_time': pd.to_datetime([
'2025-01-01 10:00:00', '2025-01-03 10:00:00', '2025-01-10 10:00:00',
'2025-01-01 09:00:00', '2025-01-02 09:00:00',
'2025-01-05 12:00:00',
]),
'value': [10, 20, 30, 5, 15, 7],
})
df = df.sort_values(['user_id', 'event_time']).reset_index(drop=True)
# 1) time since last event (aligned): transform broadcasts the per-group diff back to every row
df['time_since_last'] = df.groupby('user_id')['event_time'].transform(lambda t: t.diff().dt.total_seconds())
# 2) rolling count of events in the last 7 days (aligned): groupby(...).rolling(...) computes
# the window per user and returns rows in the same (user_id, event_time)-sorted order as the
# input, so .values assigns back positionally once df is sorted that way. Use '7D' (uppercase),
# not the deprecated lowercase '7d' alias.
df['cnt_7d'] = (
df.groupby('user_id')
.rolling('7D', on='event_time')['value']
.count()
.values
)
# 3) normalized 'value' by user mean (aligned): transform again
df['value_norm'] = df['value'] / df.groupby('user_id')['value'].transform('mean')
print(df)
# user_id event_time value time_since_last cnt_7d value_norm
# 0 1 2025-01-01 10:00:00 10 NaN 1.0 0.5
# 1 1 2025-01-03 10:00:00 20 172800.0 2.0 1.0
# 2 1 2025-01-10 10:00:00 30 604800.0 1.0 1.5
# 3 2 2025-01-01 09:00:00 5 NaN 1.0 0.5
# 4 2 2025-01-02 09:00:00 15 86400.0 2.0 1.5
# 5 3 2025-01-05 12:00:00 7 NaN 1.0 1.0
User 1's events on Jan 1, 3 and 10 give cnt_7d of 1, 2, 1: the Jan 10 event's trailing 7-day
window excludes the Jan 3 event, because pandas' default time-based window is (t - 7D, t]
(the left edge is open), and Jan 3 to Jan 10 is exactly 7 days. value_norm for user 1's values
10, 20, 30 comes out 0.5, 1.0, 1.5 against that user's mean of 20.
Key points
transformis the right tool whenever "one value per input row" is the shape you need.groupby(...).rolling(...), notgroupby().apply(), is the direct, current way to get an
aligned per-group rolling result; it sidesteps the pandas 3.0include_groupsrestriction
entirely because it was never built onapply.- Keep the DataFrame sorted by
[user_id, event_time]before any of these three operations;
diff()and time-based rolling windows both depend on that order.
Complexity
O(n log n) for the initial sort, which dominates; transform and groupby(...).rolling(...)
are each O(n) afterward, since a time-based rolling window uses a sliding pointer per group
rather than re-scanning from the start on every row, as long as the input stays sorted.
Edge cases
A user's first event has no prior event, so time_since_last is not-a-number (NaN) by
construction, not a bug; a user with a single event has a rolling count of 1; duplicate
timestamps within a user still work for both diff and rolling, but "time since last event"
becomes 0 rather than undefined; and timezone-naive and timezone-aware event_time values mixed
in the same column will not silently reconcile in pd.to_datetime, so fix that upstream before
this step, not inside it.
Trade-offs and pitfalls
The pandas 3.0 behavior change above is worth naming explicitly, because the "obvious" rewrite
of a per-user rolling window (groupby(...).apply(lambda g: g.set_index('event_time') [SOME_GROUP_COLUMN].rolling('7d').count())) now fails twice: once because pandas 3.0 excludes
the grouping column from what apply hands the function (KeyError on the group key column
inside the function), and once because the lowercase '7d' window alias is deprecated in favor
of '7D'. Both are real, verified against pandas 3.0.3. groupby(...).rolling(...) avoids the
first problem structurally (it is not built on apply) and only the second needs a one-character
fix.
transformis convenient but recomputes the group aggregate for every row unless pandas can
cache it internally; for a very large number of small groups, benchmark against a manual
mergeof a pre-aggregated table if it becomes a bottleneck.applyremains the right tool for genuinely per-group, shape-changing logic (e.g., fitting a
small model per group); just do not reach for it by default for somethingtransformor
groupby(...).rolling(...)already expresses directly.
A DataFrame loaded from a CSV is consuming far more memory than the raw data would suggest. Walk through how you would find out where the memory is actually going, and bring it down without losing information you still need. Give code for the highest-impact fix you would try first.
Sample Answer
Direct answer
Start with df.memory_usage(deep=True) to find out which columns are actually responsible for the memory, do not guess. Almost always the answer is one of three things: numeric columns stored wider than the data needs (int64/float64 when int8/float32 would hold every value), a text column that is really a small set of repeated categories, or, on current pandas, string columns still paying for the older, heavier text representation. Fix the numeric columns and the repeated-category columns first, since together they are usually the highest-impact, lowest-risk change, and they lose no information: every original value is still exactly recoverable.
Finding out where the memory is going
The two commands that answer this on any DataFrame are df.info(memory_usage="deep") (per-dtype totals and a grand total) and df.memory_usage(deep=True).sort_values(ascending=False) (the per-column breakdown, in bytes). deep=True matters on both: without it, pandas reports the size of the pointers/array structure, not the actual bytes of variable-length data like strings, which understates text-heavy columns dramatically. Concretely, on the DataFrame built below:
import pandas as pd
import numpy as np
n = 5_000
rng = np.random.RandomState(0)
df = pd.DataFrame({
"user_id": np.arange(n, dtype="int64"),
"score": rng.randint(0, 100, n).astype("int64"),
"country": rng.choice(["US", "UK", "CA", "DE", "FR"], n),
"price": rng.uniform(0, 1000, n).astype("float64"),
})
print("before:", df.memory_usage(deep=True).sum(), "bytes")
def downcast_numeric(frame):
for col in frame.select_dtypes(include=["integer", "float"]).columns:
if pd.api.types.is_integer_dtype(frame[col]):
frame[col] = pd.to_numeric(frame[col], downcast="integer")
else:
frame[col] = pd.to_numeric(frame[col], downcast="float")
return frame
def convert_to_category(frame, max_unique_ratio=0.5, max_unique=1000):
# include both 'object' and 'string' so this catches text columns under
# pandas 3.0's default string dtype as well as legacy object columns
for col in frame.select_dtypes(include=["object", "string"]).columns:
n_unique = frame[col].nunique(dropna=False)
if (n_unique / len(frame) <= max_unique_ratio) or (n_unique <= max_unique):
frame[col] = frame[col].astype("category")
return frame
df2 = downcast_numeric(df.copy())
df2 = convert_to_category(df2)
print("after:", df2.memory_usage(deep=True).sum(), "bytes")
print(df2.dtypes)
Actual output:
before: 170132 bytes
after: 40183 bytes
user_id int16
score int8
country category
price float32
dtype: object
A roughly 76% reduction, with zero information loss: user_id values all fit in int16, score (0-99) fits in int8, country has only 5 distinct values across 5,000 rows so category stores each value once and a small integer code per row, and price loses only precision beyond what float32 carries, not the values themselves in any meaningful sense for typical analysis.
Currency note verified in sandbox: pandas 3.0 changed the default in-memory representation for plain text columns from the legacy object dtype to a dedicated, more compact string dtype. df.select_dtypes(include=["object"]) alone still catches the new string dtype today for backward compatibility, but pandas emits a Pandas4Warning saying that behavior will be removed in a future version, so include=["object", "string"] (as used above) is the version-robust way to write this, it works cleanly on both current and future pandas without a warning. This also means memory-reduction advice written before pandas 3.0 will understate how much a pure string column already costs today: the new default string dtype for a ~9-character id-like column measured at roughly 18 bytes/row deep, versus roughly 59 bytes/row for the same data forced into legacy object, a real ~3.3x difference before you even apply category.
Highest-impact fix to try first
For most real datasets, numeric downcasting is the highest-impact, lowest-effort fix: it is fully automatic (pd.to_numeric(..., downcast=...) inspects the actual min/max in the column and picks the smallest safe type), reversible, and touches every numeric column in one pass. Converting low-cardinality text to category is usually the second-highest-impact change and is worth doing right after, in the same pass.
Other techniques worth knowing, roughly in order of how often they apply
- Datetime parsing: a date stored as text (
object/string) costs far more than the same value asdatetime64[ns];pd.to_datetime(col, errors="coerce")converts it and also enables fast datetime-specific operations afterward. - Sparse dtypes: for a column that is mostly zeros or mostly one repeated value (common after one-hot encoding),
pd.Series(data, dtype="Sparse[int]")stores only the non-default values plus their positions. - Selective loading: if you know only some columns are needed downstream,
usecols=atread_csvtime avoids ever materializing the rest, cheaper than loading everything and dropping columns afterward. - Drop intermediate columns as soon as they are no longer needed, rather than carrying every derived column for the life of the DataFrame.
Trade-offs and pitfalls
- Downcasting integers or floats can lose precision if you are not careful:
downcast="integer"only picks a smaller type when every value in the column actually fits, so it is safe by construction, butdowncast="float"tofloat32does trade off precision, verify that the columns you downcast do not feed into calculations sensitive to that last few bits of precision (e.g., some financial aggregations). categoryis a net win when the number of distinct values is small relative to the row count and the column is used repeatedly ingroupby, filtering, or joins (comparisons on the integer codes underneath are faster than comparing strings). It is a net loss on high-cardinality free text (ids, GUIDs, long descriptions) where the category-code table ends up almost as large as just storing the values, plus the overhead of the mapping itself.- Sparse dtypes help only when the "default" value genuinely dominates; a column that is 40% zeros is not a good sparse candidate, one that is 99.9% zeros is.
Complexity and edge cases
Complexity: downcasting and categorical conversion are each a single O(n) pass per column examined; nunique() for the category heuristic is itself an O(n) pass per candidate column, so profiling many wide, high-cardinality columns before converting has a real up-front cost worth being aware of on very wide DataFrames.
Edge cases: an all-NaN numeric column cannot be safely downcast to most integer types (no integer type represents NaN) and will either stay float64 or need a nullable integer type (Int32) instead. A column with exactly one unique value converts to category trivially and near-optimally. An empty DataFrame (len(df) == 0) makes the n_unique / len(df) ratio a division by zero, guard for that explicitly before applying the category heuristic.
Unlock Full Question Bank
Get access to all Python and Pandas for Data Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.