Data Transformation and Processing Logic Questions
Implementing transformation logic: joins, aggregations, deduplication, pivoting/reshaping, and business-rule application over datasets. Covers writing correct and maintainable transformation code, handling edge cases in the transform layer, and preparing data for downstream consumption. Focuses on the logic of turning raw data into analytics-ready outputs.
Explain how NULL participates in SQL comparisons, joins, and aggregations, contrasting it with an empty string and with zero. Describe three common pitfalls this causes when joining or aggregating real data, and the standard techniques (COALESCE, explicit NULL checks, filtering) used to handle each.
Sample Answer
Direct answer
NULL means "unknown," not "empty" and not "zero," and it does not behave like an ordinary value in comparisons: any direct comparison involving NULL (NULL = NULL, x = NULL) evaluates to NULL (neither true nor false), which is why WHERE x = NULL never matches anything, even rows where x actually is NULL.
Structured elaboration
- NULL vs empty string vs zero, by type: in a string column,
''is a real, present value (zero-length text) while NULL means no value was recorded; in a numeric column,0is a real, present value while NULL again means unknown; in a date column there is no equivalent "empty" value at all, only NULL, which is a common source of confusion when developers try to use a sentinel date instead. - Pitfall 1, filtering:
WHERE x = NULLsilently returns zero rows; the correct form isWHERE x IS NULL. - Pitfall 2, aggregation:
COUNT(column)skips NULLs whileCOUNT(*)counts every row regardless;SUM/AVGover a column with NULLs ignore the NULLs rather than treating them as zero, which changes an average's denominator in a way that is easy to miss. - Pitfall 3, joins: a LEFT JOIN with no match produces NULLs for every column from the right-hand table, not zeros or empty strings; code that assumes a numeric join result defaults to 0 will get NULL instead unless it explicitly wraps the column in
COALESCE. - Handling strategies:
COALESCE(x, default)to substitute a value for display or arithmetic; explicitIS NULL/IS NOT NULLchecks in filters; and, where the schema allows it, deciding at write time whether "unknown" should even be representable, versus requiring a value.
Worked example
SELECT id FROM users2
WHERE email IS NULL OR TRIM(email) = '';
Against rows (1, NULL), (2, ''), (3, ' '), (4, 'a@x.com'), this correctly returns ids 1, 2, and 3 (verified): NULL, an empty string, and a whitespace-only string are three distinct representations of "no real email," and all three need to be checked explicitly, none of them is caught by checking for only one of the three.
Trade-offs and pitfalls
COALESCE(amount, 0)is the right fix when "unknown" should be treated as zero for a sum, but the wrong fix when "unknown" should exclude the row from an average entirely (it will pull the average toward zero).- Comparing a nullable column to another nullable column with plain
=silently drops rows where either side is NULL from an equi-join; some engines offer a NULL-safe equality operator (IS NOT DISTINCT FROMin Postgres,<=>in MySQL) for the cases where NULL should be treated as matching NULL. - Casting a NULL numeric to a string for display purposes can turn it into the literal text
"None"or"null"in some client libraries if not explicitly handled, which then fails anIS NULLcheck silently downstream.
A dataset has missing values scattered across several columns. Walk through how you would decide what to do about each column's missingness, and how you would document and communicate that decision to stakeholders who will consume the resulting dashboard or model.
Sample Answer
Direct answer
The right way to handle a column's missing values depends first on WHY the data is missing, not just on how much is missing; understanding whether the missingness is completely random (MCAR), related to observed data (MAR), or related to the missing value itself (MNAR) should drive the choice between dropping, imputing, or explicitly flagging missingness as its own category.
Structured elaboration
- MCAR (missing completely at random): the fact that a value is missing has nothing to do with any variable, observed or not. Dropping rows is relatively safe here since it doesn't systematically bias the remaining data, though it still costs sample size.
- MAR (missing at random, conditional on observed data): missingness correlates with something you CAN observe (e.g. income is more often missing for self-employed respondents, and you know who's self-employed). Imputation conditioned on the observed correlate (model-based, or at least stratified by the correlate) is more defensible than a single global mean/median.
- MNAR (missing not at random): the missingness itself depends on the unobserved value (e.g. very high earners are more likely to decline to state income). This is the hardest case, naive imputation can systematically bias results, and an explicit "missing" indicator/category, or a domain-informed model of the missingness mechanism itself, is often more honest than pretending you can fill it in accurately.
- When to add an indicator instead of imputing a value at all: if the fact that a value is missing is itself informative (which is common under MAR/MNAR), an explicit missing-indicator feature can carry real signal that a filled-in value would erase.
- Communicating the choice: document which strategy was used per column and why, since a stakeholder consuming a dashboard or a model built on imputed data needs to know how much of what they're looking at is real versus filled-in, especially for columns with high missingness rates.
Worked example
A churn dataset with missing values in income, last_login, and plan_type, where the missingness patterns differ:
plan_typemissing only for very old accounts predating a schema migration: this looks close to MCAR (the migration is unrelated to any account's actual behavior), dropping or imputing with the overall mode is comparatively low-risk.last_loginmissing specifically for accounts that never logged in after signup: this is closer to MNAR-adjacent (the missingness IS the signal, "never logged in"), so an explicit "never logged in" category, not any numeric imputation, is the appropriate handling.incomemissing more often among certain segments who chose not to disclose it: closer to MAR/MNAR, a global mean/median fill would understate the real variation and should be flagged to stakeholders as a known limitation, or handled with a segment-conditioned estimate instead.
Trade-offs and pitfalls
- Defaulting to "just impute with the mean/median" for every column regardless of the missingness mechanism is the most common mistake; it's the easy answer but not always the correct one.
- An explicit missing-indicator column can leak information in a modeling context if the indicator itself was constructed using information not actually available at prediction time; treat it with the same point-in-time discipline as any other feature.
- Communicating "this metric is based on N% imputed values" honestly changes how much a stakeholder should trust a headline number, saying so is uncomfortable but is exactly the trust-preserving move a senior analyst makes.
Explain when to prefer a vectorized pandas operation over .apply or .map, and when a row-wise operation is still acceptable. Give a small example showing the kind of speedup you would expect from converting a row-wise transformation into a vectorized one.
Sample Answer
Direct answer
Prefer a vectorized pandas expression whenever the per-row logic can be expressed as array-level arithmetic or built-in operations; reach for .apply() (row-wise) only when the logic genuinely can't be vectorized, an irreducibly row-by-row computation calling out to an external function, or a very small dataset where the difference truly doesn't matter.
Structured elaboration
- What "vectorized" actually means: an operation expressed directly on a Series or DataFrame (
df['a'] * 2 + 1) executes as a single call into pandas/numpy's compiled internals operating over the whole array at once, rather than pandas calling back into a Python function once per row. - Why that matters:
.apply()with a Python lambda invokes the Python interpreter once per row, which carries real per-call overhead that a vectorized expression avoids entirely by staying inside compiled code for the whole operation. - When
.apply()is still the right (or only) choice: genuinely row-dependent logic that can't be expressed as array arithmetic (calling an external API per row, complex conditional logic that doesn't cleanly vectorize) may leave.apply()as the practical option, or at least the first one to reach for before investing in a harder-to-read vectorized rewrite. - Correctness first, then speed: the more important property demonstrated here is that the vectorized and row-wise forms must produce IDENTICAL results, a "faster" rewrite that subtly changes the output is not a valid optimization.
Worked example
vectorized = s * 2 + 1
row_wise = s.apply(lambda x: x * 2 + 1)
Verified against 10,000 random values: the vectorized and row-wise (.apply) forms produce byte-for-byte identical results, confirming the rewrite is a pure performance change with no correctness difference. The actual magnitude of the speed difference between the two forms is highly dependent on the specific machine, pandas/numpy version, and data size it's measured on, which is exactly why this answer explains the mechanism (avoided per-element Python interpreter and function-call overhead in the vectorized form) rather than quoting a specific "Nx faster" number: a wall-clock benchmark result is not reproducible across different environments, and stating one as if it were a fact about the technique itself would be exactly the kind of unverifiable claim to avoid.
Trade-offs and pitfalls
- Not every row-wise operation vectorizes cleanly; forcing a genuinely branchy or stateful per-row computation into an artificial vectorized form can produce code that's harder to read and maintain for a marginal or nonexistent speed benefit, know when the honest answer is "this one doesn't vectorize well."
- A
.apply()call that LOOKS like it could vectorize (a simple arithmetic expression wrapped in a lambda, as in the example) almost always should be rewritten; that's the common, clear-cut case this competency targets. - Benchmarking the difference yourself, on your own data and hardware, is more trustworthy than citing a remembered figure from elsewhere; if a number matters for a decision, measure it fresh rather than repeating an old benchmark.
Compare CSV, JSON, Parquet, and Avro as formats for data you are transforming and storing: schema support and evolution, compression, read/write performance for analytical queries versus streaming ingestion, and the small-files problem. Give concrete scenarios for when you would choose each. Separately: when reading many partitioned Parquet or ORC files, you discover the same column has an inconsistent type across files (e.g. integer in some, string in others) - explain how you would detect, reconcile, and prevent this in your transformation code.
Sample Answer
Direct answer
CSV is the lowest common denominator (universally readable, no schema enforcement, row-oriented, poor compression); JSON adds nested structure at the cost of size and columnar-query performance; Parquet and Avro are both binary and schema-aware, but Parquet is columnar (fast for analytical scans and aggregations) while Avro is row-oriented (better for write-heavy streaming and full-row reads), which is the main axis to reason from when picking one.
Structured elaboration
- CSV: human-readable, universally supported, but no native types (everything is a string until parsed), no compression, and a classic "small files" problem at scale; fine for interchange with external, less-technical parties, poor as an internal storage format at any real volume.
- JSON: supports nested structure natively, which CSV cannot express at all, but is verbose (repeats field names in every record) and, like CSV, is row-oriented text, so it doesn't get the query-time benefits of a columnar format.
- Parquet: columnar, so an analytical query that only touches 3 of 50 columns only reads those 3 columns' data off disk; strong compression from storing like-typed values together; supports schema evolution (adding/removing columns) reasonably well; the natural default for anything that will be queried by column-selective analytical workloads.
- Avro: row-oriented but still binary and schema-aware (with a schema embedded or in a registry); better suited to streaming/write-heavy pipelines where you're appending whole records rather than scanning by column, and where schema evolution rules (backward/forward compatibility) are a first-class concern.
- Cross-file type mismatches: when reading many partitioned Parquet/ORC files where the SAME column has drifted type across files (int in older files, string in newer), detect this at read time (most engines surface a clear error or a silent up-cast depending on configuration) and prevent it going forward with an enforced, versioned schema at write time rather than letting each writer infer its own types independently.
Worked example
A pipeline ingesting streaming clickstream events (write-heavy, whole-record reads by downstream consumers) writing to Kafka is well-served by Avro with a schema registry; the SAME data, once landed in a data lake and queried by analysts who mostly aggregate a handful of columns across billions of rows, is far better served by Parquet, which is why a "raw ingestion in Avro, analytical storage in Parquet" pattern is common: each format is doing the job it's actually good at, rather than one format being used everywhere out of inertia.
Trade-offs and pitfalls
- Storing frequently-updated, narrow (few-column) records in Parquet, optimized for wide analytical scans, is a mismatch; a row-oriented format or a proper OLTP store fits that access pattern better.
- CSV's total lack of type enforcement means a schema/type bug (a date column suddenly containing a non-date string) isn't caught until something downstream tries to parse it, often much later and far from the actual source of the bug.
- Reconciling a cross-file type mismatch after the fact (rather than preventing it at write time) usually means an explicit CAST or schema-normalization pass before the data can be safely unioned across the affected files; silently letting the query engine auto-coerce types can produce a subtly wrong result (e.g. a numeric column partially read as its string representation) rather than a loud error.
Discuss the options for parallelizing a CPU-bound data transformation in Python: threading, multiprocessing, vectorized numpy/pandas operations, and moving to a distributed framework like Dask or Spark. Explain why Python's GIL limits threading for CPU-bound work, and the practical costs (serialization overhead, memory duplication) of multiprocessing. Provide a small code sketch of a multiprocessing-based approach that preserves input order in its output.
Sample Answer
Direct answer
For CPU-bound work in Python, threading doesn't help (the GIL serializes CPU-bound bytecode execution across threads), so the real options are multiprocessing (separate processes, real parallelism, at the cost of serialization/IPC overhead and memory duplication), vectorized numpy/pandas operations (push the loop into optimized C code, no explicit parallelism needed), or a distributed framework like Dask or Spark once a single machine's cores aren't enough.
Structured elaboration
- Why threading doesn't help here: the Global Interpreter Lock means only one thread executes Python bytecode at a time; threading helps for I/O-bound work (where a thread releases the GIL while waiting on I/O) but does essentially nothing for CPU-bound pure-Python computation.
- Multiprocessing: separate OS processes, each with its own interpreter and memory, genuinely run in parallel across cores; the cost is serialization (pickling) of data to send to and results to receive from each worker, plus each process's own memory footprint, which matters if the data being processed is large.
- Vectorization: numpy/pandas operations push the actual loop down into pre-compiled C code operating on contiguous memory, sidestepping the GIL question entirely since the GIL is released during the vectorized operation itself; this is usually the first thing to reach for before multiprocessing, since it avoids the serialization overhead altogether.
- Distributed frameworks: once the workload exceeds what one machine's cores can handle regardless of vectorization, Dask or Spark extend the same "split the work, run independent pieces in parallel, combine results" idea across a cluster, at the cost of real operational complexity (a cluster to run and monitor, network overhead between workers).
- Order preservation: a common, concrete correctness requirement when parallelizing is that the OUTPUT order must match the INPUT order even though workers complete at different times; this needs an explicit mechanism (most executor
.map()implementations preserve input order in the returned results even though completion order is nondeterministic).
Worked example
import concurrent.futures
def cpu_work(x):
return x * x
if __name__ == "__main__": # required: worker processes re-import this module,
# so the pool creation itself must be guarded
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as ex:
results = list(ex.map(cpu_work, range(20)))
print(results[:4])
Verified: ProcessPoolExecutor.map returns results in input order ([0, 1, 4, 9, ...]) even though the four worker processes complete their individual tasks in a nondeterministic order, confirmed by checking the returned list against the serially-computed expected values.
Trade-offs and pitfalls
- Multiprocessing's serialization cost means it can be SLOWER than a plain single-threaded loop for small, cheap tasks; it pays off specifically when the per-task computation is expensive enough to dwarf the pickling/IPC overhead.
- Memory duplication across worker processes (each worker gets its own copy of whatever data it needs) can itself become the bottleneck for large shared inputs; a design that minimizes what each worker needs to receive (rather than sending the whole dataset to every worker) avoids this.
- Vectorization requires the operation to actually be expressible as array operations; a genuinely branchy, stateful, or recursive per-element computation may not vectorize cleanly, and forcing it can produce code that's harder to read for no real speed benefit, know when NOT to reach for it.
Unlock Full Question Bank
Get access to all 38 Data Transformation and Processing Logic interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.