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're preparing a free-text product review column for a bag-of-words model and notice mixed casing, stray punctuation, inconsistent unicode (curly quotes, accented characters), and some genuinely missing reviews. Walk through how you'd normalize this column, and what you'd watch out for performance-wise if it has tens of millions of rows.
Sample Answer
Direct answer
Handle genuinely missing reviews before touching the text, normalize unicode to a consistent form before lowercasing or stripping punctuation (order matters), and do the whole thing with vectorized .str accessor methods rather than .apply or a Python loop, since at tens of millions of rows that choice alone is the difference between minutes and hours.
Structured elaboration, in the order I'd apply it
- Missing reviews first. Check
df['review'].isna()and decide whether to drop those rows for the bag-of-words model or keep them with an explicitis_missingindicator, since "left no review" can itself be predictive (it may correlate with rating). Don't conflate a realNaN(not-a-number) with placeholder strings an earlier pipeline stage may have written, like'n/a'or'none'; check for both explicitly. - Unicode normalization before anything else touches the text. Curly ("smart") quotes and accented characters otherwise get mangled by later regex steps, or split what should be one word into two different tokens. Unicode NFKD normalization decomposes an accented character into a plain base letter plus a separate combining accent mark, which you can then strip:
import pandas as pd
df = pd.DataFrame({'review': [
"Great product, LOVED it!!",
"Terrible... würde nie wieder kaufen",
None,
]})
df['review_clean'] = (
df['review']
.str.normalize('NFKD')
.str.encode('ascii', 'ignore')
.str.decode('ascii')
)
- Lowercase and strip punctuation with vectorized
.strmethods, never a Python-level loop:
df['review_clean'] = df['review_clean'].str.lower()
df['review_clean'] = df['review_clean'].str.replace(r'[^\w\s]', ' ', regex=True)
df['review_clean'] = df['review_clean'].str.replace(r'\s+', ' ', regex=True).str.strip()
Worked example
Two reviews that look like they should end up as the same tokens, but do not: one with a curly apostrophe from the start, one with a plain straight apostrophe from the start.
import pandas as pd
df = pd.DataFrame({'review': [
"Cafe’s GREAT!! Best review ever", # curly apostrophe
"Cafe's great too, ever", # straight apostrophe
]})
df['review_clean'] = (
df['review']
.str.normalize('NFKD')
.str.encode('ascii', 'ignore')
.str.decode('ascii')
)
print(df['review_clean'].tolist())
df['review_clean'] = df['review_clean'].str.lower()
df['review_clean'] = df['review_clean'].str.replace(r'[^\w\s]', ' ', regex=True)
df['review_clean'] = df['review_clean'].str.replace(r'\s+', ' ', regex=True).str.strip()
print(df['review_clean'].tolist())
Output (verified by running this exact code):
['Cafes GREAT!! Best review ever', "Cafe's great too, ever"]
['cafes great best review ever', 'cafe s great too ever']
After NFKD plus ascii-encode/ignore: the curly-apostrophe review becomes "Cafes GREAT!! Best review ever", the apostrophe is gone with nothing left in its place. NFKD has no decomposition for typographic quote marks, so ascii-ignore just deletes the character outright. The straight-apostrophe review is untouched by this step (it was already plain ASCII).
After lowercasing, punctuation-strip, and whitespace collapse: the curly-apostrophe review ends as "cafes great best review ever", one token, cafes. The straight-apostrophe review ends as "cafe s great too ever", because the punctuation-strip regex replaces the surviving apostrophe with a space, splitting cafe's into two tokens, cafe and s.
So this pipeline does not make the two spellings converge to the same bag-of-words tokens, which is easy to assume incorrectly. If that convergence matters for your corpus, explicitly map common typographic punctuation to its ASCII equivalent before relying on NFKD, e.g. df['review'].str.replace('’', "'", regex=False), so a curly apostrophe becomes a real apostrophe and both spellings hit the punctuation-strip step identically.
Performance at tens of millions of rows
- Stick to
.straccessor methods (vectorized, C-optimized under the hood) instead of.apply(lambda x: ...)or a Pythonforloop over rows. - Each
.str.replace()call scans the full column and allocates a newSeries. Chaining four or five of them means four or five full passes plus several temporary full-length copies of the string column, which is often the real memory bottleneck rather than the final cleaned result. Where practical, combine multiple regex substitutions into fewer passes, or process the column in chunks (pd.read_csv(chunksize=...)) so several full copies are never held in memory at once. str.normalize()and complex regexes tend to be the slowest per-character steps. Benchmark on a real sample (e.g. 100k rows) before assuming the full pipeline runs fast enough; don't guess.- If that is still too slow, look at Dask or Polars for out-of-core or multi-core string processing. For most tens-of-millions-row batch jobs, vectorized pandas
.strmethods on chunked reads are usually enough on their own.
Trade-offs and pitfalls
- Emojis: decide whether to strip them or keep them as a signal, they survive NFKD/ascii-ignore differently depending on their Unicode form.
- Leftover HTML markup if the reviews were scraped from a webpage needs its own stripping step; NFKD does nothing about
<br>tags. - Non-English reviews: NFKD plus ascii-encoding will silently strip non-Latin scripts (Chinese or Arabic text, for example) down to nothing. If the corpus is multilingual, filter or language-detect before applying ASCII normalization rather than after, or you lose that data with no error raised.
A pivot_table produced hierarchical columns like ('sales','sum') and ('sales','mean'). Write robust pandas code to flatten MultiIndex columns into single strings like 'sales_sum' and ensure deterministic ordering. Also describe how to handle potential duplicate names after flattening and how to avoid clashing column names.
Sample Answer
Direct answer
Join each MultiIndex column tuple's levels (a MultiIndex is a hierarchical index whose single axis carries more than one level of labels, e.g. the tuple ('sum', 'sales')) into a single string with a fixed separator, in a fixed left-to-right level order, then walk the resulting names once to detect and disambiguate any duplicates with deterministic numeric suffixes. Deterministic ordering matters because two runs of the same pipeline should always assign the same flattened name to the same original column, so a random or hash-based disambiguation scheme is the wrong tool here.
Structured elaboration
- A pivot table's columns after
pivot_table(..., aggfunc=[...])areMultiIndextuples like('sum', 'sales'); joiningstr(level)for each level with"_"produces'sum_sales'. - Normalize each level value before joining:
Nonebecomes an explicit empty-string placeholder (not the literal text"None"), and non-string levels (numbers,Timestampobjects) get coerced withstr()so the join never fails on a mixed-type level. - After building the base names, do a single deterministic pass: the first occurrence of a name is kept as-is, and every subsequent collision gets
_1,_2, ... appended, checking against names already assigned so a suffix can't itself collide with an unrelated column that happens to already use that name. - Set
df.columns = final_namesonce at the end rather than renaming incrementally, so the operation is a single clear step.
Worked example
import pandas as pd
def flatten_columns(df, sep="_", na_rep=""):
cols = df.columns
tuples = list(cols) if isinstance(cols, pd.MultiIndex) else [(c,) for c in cols]
def norm(x):
return na_rep if x is None else (x if isinstance(x, str) else str(x))
base_names = []
for t in tuples:
parts = [p for p in (norm(level) for level in t) if p != ""]
base_names.append(sep.join(parts) if parts else (na_rep or "col"))
seen, final = {}, []
for name in base_names:
if name not in seen:
seen[name] = 0
final.append(name)
else:
seen[name] += 1
candidate = f"{name}{sep}{seen[name]}"
while candidate in seen:
seen[name] += 1
candidate = f"{name}{sep}{seen[name]}"
seen[candidate] = 0
final.append(candidate)
out = df.copy()
out.columns = final
return out
raw = pd.DataFrame({
'region': ['N', 'N', 'S', 'S'],
'sales': [100, 200, 150, 300],
'units': [10, 20, 15, 30],
})
pv = raw.pivot_table(index='region', values=['sales', 'units'], aggfunc=['sum', 'mean'])
flat = flatten_columns(pv)
print(flat.columns.tolist())
# ['sum_sales', 'sum_units', 'mean_sales', 'mean_units']
# duplicate-name scenario: two columns that would flatten to the same string
mi = pd.MultiIndex.from_tuples([('sales', 'sum'), ('sales_sum', '')])
df_dup = pd.DataFrame([[1, 2], [3, 4]], columns=mi)
print(flatten_columns(df_dup).columns.tolist())
# ['sales_sum', 'sales_sum_1']
Verified: on the pivot_table output above, the flattened names come back exactly as sum_sales/sum_units/mean_sales/mean_units, and the duplicate-name case, one MultiIndex column ('sales', 'sum') alongside a plain column already named 'sales_sum', resolves to ['sales_sum', 'sales_sum_1'] rather than silently overwriting one with the other.
A cleaner alternative worth naming. If the MultiIndex is coming from a groupby(...).agg(...) call rather than pivot_table, named aggregation sidesteps the flattening problem entirely: df.groupby('region').agg(sales_sum=('sales', 'sum'), sales_mean=('sales', 'mean')) produces single-level string columns (sales_sum, sales_mean) directly, with no MultiIndex ever created. Verified this returns flat columns immediately. It doesn't help with pivot_table specifically (which always produces a MultiIndex when multiple aggregations are requested), but it's the better default whenever groupby.agg is the actual source of the hierarchy.
Trade-offs and pitfalls
- Complexity:
O(n * L)wherenis the number of columns andLis the number of index levels; memory isO(n)for the new name list. - Edge cases: a single-level (non-MultiIndex) DataFrame passed in falls through the
elsebranch unchanged in shape (no crash); levels that are entirely empty strings across all columns fall back to thena_repplaceholder or a literal"col"name rather than producing an empty string column name; very long concatenated names (many levels, long category names) may want truncation or a shorter separator depending on downstream tooling that has column-name-length limits. - The most common real mistake is picking a separator that already appears inside a level's own value (a category literally named
"sales_total"combined with a"_"separator becomes ambiguous with a genuinely two-levelsales+totalpair); pick a separator unlikely to appear in the data, or validate against it explicitly before shipping the flattened names downstream.
You need to pivot a dataset with a high-cardinality 'metric' column (thousands of distinct metric names) into a wide table, but any single product-date only ever has values for a handful of those metrics. A naive pivot_table would create an enormous, mostly-empty matrix. Propose a memory-efficient way to produce this wide table and show code for it.
Sample Answer
Direct answer
Don't build the dense matrix at all. Keep the data long-form (one row per product-date-metric) as the source of truth, and only materialize a wide view for a bounded subset of metrics you actually need at once, using pandas' SparseDtype so the empty cells never occupy real memory. A full dense pivot allocates a cell for every (product-date, metric) pair even though any single product-date only touches a handful, so a thousand-metric catalogue turns a few thousand real values into millions of stored NaN (not-a-number, pandas' missing-value marker) cells.
Approach
- Aggregate to a compact, sparse-friendly representation: for each product-date, keep only the metrics that are actually present, as a dict/JSON payload rather than a row of mostly-empty columns.
- If a tabular wide view is genuinely needed (for a model or a dashboard), pivot only the metrics of interest and store the result with
pandas.SparseDtype, which keeps non-fill values plus their positions instead of one cell per (row, column) pair. - For downstream analytics or machine learning that wants a full matrix, build a
scipy.sparsecoordinate (COO, coordinate-format sparse matrix storing (row, column, value) triples instead of a dense grid) matrix directly, never a dense pandas pivot.
import pandas as pd
import numpy as np
import json
from scipy import sparse
def to_sparse_long(df, id_cols=("product_id", "date"), metric_col="metric", value_col="value"):
"""One row per (product_id, date) holding only the metrics present that day, as JSON."""
grouped = (
df.groupby(list(id_cols))
.apply(lambda g: dict(zip(g[metric_col], g[value_col])), include_groups=False)
.rename("metrics_dict")
.reset_index()
)
grouped["metrics_json"] = grouped["metrics_dict"].apply(json.dumps)
return grouped[[*id_cols, "metrics_json"]]
def to_sparse_wide(df, metrics_of_interest, id_cols=("product_id", "date"),
metric_col="metric", value_col="value"):
"""Wide pivot restricted to a bounded metric set, stored as pandas SparseDtype."""
subset = df[df[metric_col].isin(metrics_of_interest)]
wide = subset.pivot_table(index=list(id_cols), columns=metric_col,
values=value_col, aggfunc="first")
for c in wide.columns:
wide[c] = wide[c].astype(pd.SparseDtype(np.float64, np.nan))
return wide
def to_coo_matrix(df, id_cols=("product_id", "date"), metric_col="metric", value_col="value"):
"""Full (product-date x metric) matrix as a scipy COO sparse matrix, no dense pandas pivot."""
row_key = list(df[list(id_cols)].itertuples(index=False, name=None))
row_map = {k: i for i, k in enumerate(dict.fromkeys(row_key))}
metric_map = {m: i for i, m in enumerate(df[metric_col].unique())}
rows = [row_map[k] for k in row_key]
cols = [metric_map[m] for m in df[metric_col]]
return sparse.coo_matrix((df[value_col].to_numpy(), (rows, cols)),
shape=(len(row_map), len(metric_map)))
Key points:
- The long-form JSON table (
to_sparse_long) is O(non-zero entries) in storage and is the right form to persist to parquet for a BI tool that can unpack a JSON column, or serve on demand via an API. pandas.SparseDtypeis for when you genuinely need a small number of columns as real DataFrame columns (feature selection for a model, a report) without paying for every empty cell.scipy.sparse.coo_matrixis the right structure for the FULL matrix when something downstream (a model, a similarity computation) needs the whole (product-date x metric) space at once.
Worked example
df = pd.DataFrame([
{"product_id": "A", "date": "2025-01-01", "metric": "m1", "value": 10},
{"product_id": "A", "date": "2025-01-01", "metric": "m20000", "value": 5},
{"product_id": "B", "date": "2025-01-01", "metric": "m2", "value": 7},
])
print(to_sparse_long(df))
print()
wide = to_sparse_wide(df, metrics_of_interest=df["metric"].unique())
print(wide)
print(wide.dtypes)
print()
print(to_coo_matrix(df).toarray())
Output (verified against pandas 3.0.3):
product_id date metrics_json
0 A 2025-01-01 {"m1": 10, "m20000": 5}
1 B 2025-01-01 {"m2": 7}
metric m1 m2 m20000
product_id date
A 2025-01-01 10.0 NaN 5.0
B 2025-01-01 NaN 7.0 NaN
metric
m1 Sparse[float64, nan]
m2 Sparse[float64, nan]
m20000 Sparse[float64, nan]
dtype: object
[[10 5 0]
[ 0 0 7]]
Only 3 values exist across 2 product-dates and 3 metrics, but a naive pivot over the real thousands-of-metrics catalogue would allocate a dense (product-dates x metrics) grid; here it is a 2x3 grid to illustrate the shape, and every metric cell not actually observed for that product-date is absent from storage in the long form and only a lightweight fill-value entry in the sparse-dtype and COO forms.
Complexity and edge cases
Complexity: building the long-form grouped table is O(n) time and O(k) storage where k is the number of non-zero (product-date, metric) entries, versus O(rows x thousands-of-metrics) for a naive dense pivot. The SparseDtype wide view and the COO matrix are both O(k) storage for the values plus O(k) for their position indices, a constant-factor overhead over the long form, still far below dense.
Edge cases: duplicate (product-date, metric) rows need an explicit aggregation choice (aggfunc="first", "last", or "mean") or pivot_table silently picks one; a metric present for one product-date but never elsewhere still gets its own sparse column once selected into metrics_of_interest; extremely large per-row JSON payloads (a product-date with hundreds of metrics present) should go to parquet/object storage rather than staying as an in-memory string column; a product_id/date combination with zero rows never appears at all in the long form, so any downstream join needs an explicit outer join against the full key space if "no data that day" must be distinguished from "value is genuinely zero".
Trade-offs and pitfalls
Long-form JSON storage is the cheapest and most flexible (any BI tool or API can read a subset of keys), but it pushes the reshape work downstream to whoever consumes it. SparseDtype gives you a real, indexable DataFrame with column-level operations, at the cost of only being practical for a bounded metric subset, not the full thousands-wide catalogue, since selecting and materializing that many sparse columns still carries per-column overhead. The COO matrix is the most memory-efficient full-matrix representation and is what you want for downstream linear algebra or ML, but it loses the readable row/column labels unless you keep the row_map/metric_map alongside it. The pitfall to avoid is reaching for pivot_table directly on the full metric set out of habit: pandas will build the dense matrix in memory before you ever get a chance to convert it to a sparse dtype, so the peak memory spike happens regardless of what dtype the result ends up with.
You are given a free-text column 'customer_notes' containing entries such as 'Order 12345: delayed due to weather; ETA 2024-05-10' and other inconsistent formats. Demonstrate using pandas vectorized string methods or regex to extract order numbers, reason, and ETA date into separate columns, handling missing or malformed entries gracefully. Discuss performance tips for regex-heavy operations on millions of rows.
Sample Answer
Direct answer
Pull the three fields with separate, narrowly-scoped .str.extract() calls (one regex per field) rather than one mega-regex with several optional named groups. A single combined pattern with .*? lazy gaps between optional groups is fragile: it is easy to write one that compiles and "runs" but silently returns empty or missing values for cases it was meant to catch. Coerce the ETA with pd.to_datetime(..., errors='coerce') so malformed dates become NaN (not-a-number, pandas' missing-value marker) instead of raising, and leave order_id / reason as NaN when the note does not contain them.
Approach
- Write one small, targeted regex per field instead of one large regex trying to capture everything positionally.
- Require the order id to contain at least one digit (via a lookahead) so the word "order" appearing without an id (e.g. "No order info") does not falsely match on the next word.
- Run each regex with
Series.str.extract, which is vectorized (implemented in pandas' compiled extension code, not a Python-level loop). - Normalize the two accepted ETA separators (
-and/) to one, then parse with an explicitformat=anderrors='coerce'.
Worked example
import re
import pandas as pd
df = pd.DataFrame({
"customer_notes": [
"Order 12345: delayed due to weather; ETA 2024-05-10",
"ETA:2024/06/01; order#98765 - late",
"No order info, customer canceled",
None,
"Order: ABC123; ETA unknown",
]
})
order_re = re.compile(r"(?i)\border[:#]?\s*(?P<order_id>(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]+)")
reason_re = re.compile(r"(?i)\b(?P<reason>delayed(?: due to [^;.,]+)?|late|cancell?ed|returned|damaged)\b")
eta_re = re.compile(r"(?i)ETA[:\s]*(?P<eta_raw>\d{4}[-/]\d{2}[-/]\d{2})")
notes = df["customer_notes"]
order_id = notes.str.extract(order_re)["order_id"]
reason = notes.str.extract(reason_re)["reason"]
eta_raw = notes.str.extract(eta_re)["eta_raw"]
eta = pd.to_datetime(eta_raw.str.replace("/", "-", regex=False), format="%Y-%m-%d", errors="coerce")
out = df.assign(order_id=order_id, reason=reason, eta=eta)
print(out[["order_id", "reason", "eta"]])
Output (verified against pandas 3.0.3):
order_id reason eta
0 12345 delayed due to weather 2024-05-10
1 98765 late 2024-06-01
2 NaN canceled NaT
3 NaN NaN NaT
4 ABC123 NaN NaT
Row 2 has no order id (the note only says "No order info"), row 3 is a fully missing note (None), and row 4 has an unparseable ETA ("unknown"): all three land as NaN or NaT (not-a-time, pandas' missing marker for datetime data) rather than raising or silently mis-extracting.
Key points
- Compile each regex once (
re.compile) and reuse it;.str.extractaccepts a compiled pattern directly. - The digit lookahead
(?=[A-Za-z0-9-]*\d)on the order id is what keeps "No order info" from false-matching "info" as an order id. Without it, any word after "order" would be captured. - Keep the three extractions independent. Interleaving them into one pattern with optional groups and lazy wildcards is exactly the failure mode above: it looks compact, but each optional group's success depends on how the lazy
.*?between them consumed the string, which is not something you can verify by eye.
Complexity
Each .str.extract call is a single vectorized pass over the Series: O(n) in the number of rows, with per-row cost dominated by the regex engine rather than by pandas. Memory: .str.extract returns a new DataFrame per call, so three calls materialize three intermediate frames of about n rows each, and .assign copies that data into the final frame. For very wide free-text extraction (many fields), several small targeted patterns concatenated column-wise are usually cheaper than one very wide regex, because a single catastrophic-backtracking pattern can turn what looks like O(n) into effectively O(n times k) with a large hidden constant k.
Edge cases
- Missing note (
None/NaN):.str.extractpropagates a missing input to missing output without raising;eta_rawfor that row is NaN, sopd.to_datetimeon it stays NaT. - No match at all (row 2): every group for that row is NaN; do not assume at least one field always fills in.
- Ambiguous separators: the pattern matches both
-and/for the ETA; if the underlying data mixesMM/DD/YYYYandDD/MM/YYYYfor the slash form, that is a genuinely unresolvable ambiguity from the text alone and should be flagged, not silently guessed at.
Performance tips for millions of rows
- Prefer
Series.strmethods (.str.extract,.str.contains) over.apply()with a Python-level regex loop, since the former runs in pandas' vectorized layer. - Pre-compile every regex and pass the compiled object in, not a fresh string each call.
- Keep each pattern narrow and anchored; avoid nested quantifiers that can backtrack catastrophically on adversarial or unexpectedly long text.
- For genuinely large volumes, read and process in chunks (
pd.read_csv(chunksize=...)) or move to an out-of-core engine (Dask, Polars) once a single machine's memory becomes the bottleneck. - Benchmark on a representative sample before committing: several small, simple extracts are frequently faster in aggregate than one large regex trying to do everything in one pass, and they are far easier to debug when a field comes back wrong.
Write pandas code to remove groups with fewer than 3 transactions per customer in DataFrame df_orders where each group is defined by customer_id. Use groupby.filter and explain how groupby.filter differs from groupby.transform in terms of return shape and alignment.
Sample Answer
Direct answer: groupby.filter keeps or drops an entire group's rows based on a predicate you write over that group, so df_orders.groupby('customer_id').filter(lambda g: len(g) >= 3) removes every row belonging to a customer with fewer than 3 transactions and keeps everyone else's rows untouched.
Structured elaboration and worked example (verified, pandas 3.0.3):
import pandas as pd
df_orders = pd.DataFrame({
'customer_id': [1, 1, 1, 2, 2, 3, 3, 3, 3],
'order_id': [101, 102, 103, 201, 202, 301, 302, 303, 304],
'amount': [10, 20, 30, 15, 25, 5, 6, 7, 8],
})
df_filtered = df_orders.groupby('customer_id').filter(lambda g: len(g) >= 3)
print(df_filtered)
Verified output: customer 2 (2 transactions) is dropped entirely; customers 1 (3 transactions) and 3 (4 transactions) come back unchanged, in their original row order, with the original index preserved. An equivalent transform-based rewrite produces byte-identical output on the same fixture:
mask = df_orders.groupby('customer_id')['order_id'].transform('count') >= 3
print(df_orders[mask])
print(df_filtered.equals(df_orders[mask]))
(df_filtered.equals(df_orders[mask]) is True.)
filter vs. transform, the actual distinction
groupby.filter(predicate) | groupby.transform(func) | |
|---|---|---|
| Return shape | A subset of the original DataFrame, same columns, only some rows | A Series/DataFrame the same length as the original, no rows removed |
| What the function returns per group | A single boolean, whole group kept or dropped | A value broadcast back to every row in that group |
| Alignment to the original frame | Rows are physically removed, remaining index is a subset of the original | Every original row gets an aligned value, index matches the input exactly |
| Typical use | "Drop groups that don't meet a group-level condition" | "Compute a group-level stat and attach it to every row in that group" (e.g. group mean as a new column) |
Key points
filterevaluates the predicate once per group on the whole group slice;transformevaluates a function per group but must return something broadcastable back to every row, it cannot change how many rows exist.- The
transform-plus-boolean-mask rewrite above achieves the same result asfilterhere specifically because the condition ("group size >= 3") happens to reduce to a per-row boolean once broadcast; not everyfilterpredicate has an equally simpletransformequivalent.
Complexity: both approaches are O(n) in the number of rows for a group-size predicate: filter computes len(g) per group (O(n) total across all groups) then does one boolean selection pass (O(n)); transform('count') is a single vectorized pass with no per-group Python-level callback, which is typically faster for a plain built-in aggregation like 'count' because it avoids invoking a Python lambda once per group. filter with an arbitrary Python lambda predicate pays that per-group call overhead; prefer the transform + boolean-mask form when the predicate can be expressed as one, as here.
Edge cases
- No group meets the threshold:
filterreturns an emptyDataFramewith the original columns and dtypes preserved (verified:int64columns stayint64on the empty result, not coerced toobject). - A customer with exactly 3 transactions: kept,
>=not>, verify the boundary condition matches what "fewer than 3" actually means before shipping (fewer than 3 means drop groups withlen(g) < 3, equivalently keeplen(g) >= 3). - Missing
customer_id(NaN, not-a-number, pandas' missing-value marker): by defaultgroupbyexcludesNaNkeys entirely, so those rows never reach the predicate at all, they are silently dropped by grouping, not byfilter. If null customer ids must be evaluated as their own group, passgroupby('customer_id', dropna=False)explicitly. - Duplicate order rows for the same customer:
filtercounts rows, not distinct transactions, if duplicates need to be deduplicated before the size check, do that before grouping, not after.
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.