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.
Explain what NaN represents in NumPy/pandas, why comparisons like (np.nan == np.nan) return False, and list safe ways to test for missing values in a DataFrame that also work for non-numeric dtypes.
Sample Answer
Direct answer
NaN ("not-a-number") is the IEEE 754 floating-point sentinel that pandas uses by default for missing numeric data. Because IEEE 754 defines NaN as unordered, every comparison against it, including nan == nan, evaluates to False, so == can never be used to detect missing values. The safe, dtype-agnostic test is pd.isna() (or the equivalent .isna() method), which also correctly recognizes None and NaT and works on non-numeric columns where a bare np.isnan() would fail.
Structured elaboration
Why the comparison is False. IEEE 754 treats NaN as "unordered": any relational comparison involving it, ==, <, >, including comparing it to itself, returns False. This is a deliberate design choice so that two unknown values are never silently treated as equal.
Safe ways to test for missingness:
pd.isna(x)/pd.notna(x): module-level functions that work on scalars, Series, and DataFrames alike, and recognizeNaN,None, andNaT(the missing-value marker for datetime columns).df.isna()/df.notna(): the equivalent DataFrame/Series methods, returning a boolean mask of the same shape.np.isnan(arr): only safe for arrays of actual floats; it raises on object-dtype columns (mixed types, strings), so preferpd.isna()unless you know the column is a pure float array.
Currency note. Nullable dtypes ("Int64", "boolean", "string") use a separate sentinel, pd.NA, instead of np.nan. pd.NA follows three-valued logic rather than IEEE 754: pd.NA == pd.NA returns pd.NA itself (an "unknown" result), not a guaranteed False the way np.nan == np.nan is. pd.isna() detects pd.NA correctly either way, which is exactly why it is the dtype-agnostic tool to reach for instead of a dtype-specific comparison.
Worked example
import pandas as pd
import numpy as np
df = pd.DataFrame({'x': [1, np.nan, 3], 'y': ['a', None, 'c']})
df.isna()
# x y
# 0 False False
# 1 True True
# 2 False False
df[df['x'].isna()]
# x y
# 1 NaN None
np.nan == np.nan # False
pd.isna(np.nan) # True
pd.isna(None) # True
s = pd.Series([1, None, 3], dtype="Int64") # nullable integer dtype
s
# 0 1
# 1 <NA>
# 2 3
s.isna()
# 0 False
# 1 True
# 2 False
pd.NA == pd.NA # <NA> (not True, not False)
Trade-offs and pitfalls
Don't rely on isinstance(x, float) plus math.isnan(x) as a general check: it breaks the moment a column has mixed or non-numeric dtype, which is exactly where pd.isna() still works. Don't filter with df[df['x'] == np.nan], it silently returns zero rows every time rather than raising, which is easy to miss in review. When a comparison on a nullable-dtype column produces a mask that itself contains pd.NA (e.g. s2 > 1 on an Int64 Series with a missing value), boolean indexing with that mask treats the <NA> entries as excluded, the same as False, so filtering still behaves sensibly, but arithmetic or logical combination of that mask with &/| should still be reasoned about explicitly rather than assumed.
You are given a CSV file data.csv (comma-separated, header in the first row). 1) Load it into a DataFrame, parsing a column named event_time as datetime. 2) Print the first 5 rows and a concise summary (info) including non-null counts and dtypes. 3) Select only the columns ['user_id', 'event_time', 'value'] and filter rows where value > 0 and event_time falls in calendar year 2021. 4) Show how you would handle rows with malformed dates during parsing.
Sample Answer
Direct answer
Load the file with read_csv, then explicitly convert event_time with pd.to_datetime(..., errors='coerce') as a separate step rather than relying on read_csv's own parse_dates argument to handle bad rows. That distinction matters: parse_dates has no error-tolerant mode, if even one value in the column fails to parse, pandas silently leaves the entire column as plain strings instead of converting the good rows and marking the bad one, so any downstream code that assumes it's working with real datetimes breaks without warning.
Structured elaboration
- Load, keeping
user_idas a string (preserves any leading zeros) and doing datetime conversion as its own explicit step. - Inspect with
head()andinfo(), which reports non-null counts and dtypes per column, this is exactly where a silently-unparsed date column would show up asobject/string instead ofdatetime64. - Select and filter: subset to the three requested columns, then filter on
value > 0and on the event falling within calendar year 2021. - Handle malformed dates explicitly by coercing to
NaT(pandas' null value for datetimes) rather than raising, and by capturing which rows were malformed for follow-up rather than silently discarding them.
Worked example
import pandas as pd
# 1) load, convert event_time explicitly (not via read_csv's parse_dates)
df = pd.read_csv("data.csv", dtype={"user_id": str})
df["event_time"] = pd.to_datetime(df["event_time"], errors="coerce")
# 2) first 5 rows and a concise summary
print(df.head(5))
df.info()
# 3) select columns, filter value > 0 and year == 2021
df["value"] = pd.to_numeric(df["value"], errors="coerce")
sub = df[["user_id", "event_time", "value"]].copy()
mask = (sub["value"] > 0) & (sub["event_time"].dt.year == 2021)
result = sub.loc[mask]
# 4) malformed dates become NaT; capture them rather than silently dropping
malformed = df[df["event_time"].isna()]
if not malformed.empty:
malformed.to_csv("malformed_event_time_rows.csv", index=False)
Verified against a 6-row fixture where one row's event_time is the literal string "not-a-date": with the explicit pd.to_datetime(..., errors='coerce') step, that row correctly becomes NaT while every other row parses to a real Timestamp, df.info() correctly reports event_time as datetime64[us] with 5 of 6 non-null, and the year/value filter correctly excludes both the malformed row and the out-of-range/non-positive rows, leaving exactly the one row that is genuinely 2021 and positive.
Trade-offs and pitfalls
- The reproducibility bug worth calling out explicitly: passing
parse_dates=["event_time"]directly toread_csvon this exact fixture does not produceNaTfor the bad row, it silently leaves the wholeevent_timecolumn as plain strings, dtypeobject/str, with no error and no warning. This was reproduced directly:pd.read_csv("data.csv", parse_dates=["event_time"])on a file containing one malformed date returns a column that still reportsdtype: str, and any later comparison likesub['event_time'] >= pd.to_datetime('2021-01-01')then raisesTypeError: Invalid comparison between dtype=str and Timestampinstead of filtering correctly. Confirmed separately thatparse_datesdoes correctly producedatetime64when every value in the column happens to be valid, so the failure is specific to the presence of malformed rows, exactly the scenario the question is asking about. The safe pattern is to load the column as-is and convert it explicitly withpd.to_datetime(..., errors='coerce')afterward, which degrades gracefully toNaTper-row instead of abandoning the whole column. - Filtering with
.dt.year == 2021is simpler and less error-prone than constructing explicit start/endTimestampboundaries, and it naturally excludesNaTrows (aNaTcomparison is alwaysFalse), so malformed rows are automatically excluded from the year filter without extra code. - Complexity: everything here is a single linear pass,
O(n)time for the load, the datetime/numeric coercion, and the boolean-mask filter, andO(n)memory for holding the loaded frame (plus a second, smallerO(k)copy for thekmalformed rows written out separately). Nothing here requires more than one pass over the data or a full in-memory copy beyond the loaded frame itself. - Edge cases: an entirely empty file, or one where
event_timeis missing from the header, should fail fast with a clear error rather than proceeding silently; avaluecolumn containing non-numeric strings is coerced toNaN(not-a-number, pandas' missing-value marker) bypd.to_numeric(..., errors='coerce')and then naturally excluded byvalue > 0(since aNaNcomparison is alsoFalse), which is convenient but worth flagging explicitly to whoever owns data quality, since bad values disappear from the result set without a visible error. - Persisting the malformed rows to a side file, rather than just dropping them, is what makes this auditable: silently dropping bad rows hides a data-quality problem; logging them (or writing them somewhere reviewable) surfaces it.
Given a sample DataFrame df with columns ['id', 'name', 'age', 'signup_date', 'score'] demonstrate with code and explanations the differences between df.loc, df.iloc and chained indexing. Show examples selecting rows 10-20, selecting by boolean condition (age > 30), selecting columns by label and by integer positions. Explain why chained indexing can be dangerous and how to avoid it.
Sample Answer
Direct answer
.loc selects by label with an inclusive slice endpoint, .iloc selects by integer position with an exclusive slice endpoint, matching a Python list slice. Chained indexing, two indexing operations performed back to back such as df[df['age'] > 30]['score'] = value, is dangerous because under pandas' Copy-on-Write (CoW) engine the first indexing step always produces an independent copy, so the second step's assignment can land on that throwaway copy and leave the original df completely unchanged. The fix is to do the row selection and the column write in a single .loc call: df.loc[cond, 'col'] = value.
Approach
import pandas as pd
df = pd.DataFrame({
'id': range(30),
'name': [f"u{i}" for i in range(30)],
'age': [20 + (i % 50) for i in range(30)],
'signup_date': pd.date_range("2020-01-01", periods=30, freq='D'),
'score': [i * 0.5 for i in range(30)],
})
# Rows 10-20
rows_loc = df.loc[10:20] # 11 rows: labels 10 through 20, BOTH inclusive
rows_iloc = df.iloc[10:21] # 11 rows: positions 10 through 20, stop 21 EXCLUDED
# Boolean condition
cond_rows = df.loc[df['age'] > 30]
# Columns by label and by position
cols_label = df.loc[:, ['id', 'age', 'score']]
cols_pos = df.iloc[:, [0, 2, 4]]
# DANGEROUS: chained indexing (single expression)
df[df['age'] > 30]['score'] = 999
# pandas raises the ChainedAssignmentError warning at this line, and df is untouched
# ALSO DANGEROUS, and silent: chained indexing across two statements
subset = df[df['age'] > 30]
subset['score'] = subset['score'] * 1.1
# NO warning at all here: subset is already an independent copy, so the assignment
# succeeds on subset only; df is never touched, and nothing signals that anything happened
# SAFE: row and column selection in one .loc call
df.loc[df['age'] > 30, 'score'] = df.loc[df['age'] > 30, 'score'] * 1.1
Key points
rows_locandrows_ilocare identical here (11 rows each) only because reaching position 20 by label and by "stop at 21" both land on the same rows; the inclusive/exclusive difference is what makes the two slice expressions (10:20vs10:21) necessary to get the same result.- The single-expression chain (
df[cond]['score'] = value) IS detected by pandas: it raises theChainedAssignmentErrorwarning at the point of assignment, and the original frame is left unchanged. - The two-statement chain (
subset = df[cond];subset['score'] = ...) is NOT detected: by the time you mutatesubset, pandas has no way to know you intended it to represent a piece ofdf, so the write lands cleanly onsubsetalone, with zero warning of any kind. This is the more dangerous shape precisely because nothing looks wrong. SettingWithCopyWarningwas removed from pandas entirely as of 3.0. If you are reading older material describing it, that warning class no longer exists; the CoW-era failure modes are theChainedAssignmentErrorwarning (visible) and the silent two-statement case above (not visible).
Complexity
.loc label lookups are backed by the index's hash table, close to O(1) average per label, so selecting k rows by label is roughly O(k). .iloc positional lookups are direct offset arithmetic, O(k) for k positions. A boolean-mask selection like df['age'] > 30 is O(n) to build the mask over all n rows, plus O(k) to materialize the k matching rows. Chained assignment costs nothing extra algorithmically: the danger is purely correctness (the write silently lands nowhere useful), not performance.
Edge cases
- Duplicate index labels:
df.loc[label]returns every row carrying that label, which can silently expand what you expected to be a single row;.ilocis unaffected since it always addresses exactly one position. - No rows match the condition:
.loc/boolean selection returns an empty (0-row) DataFrame, not an error, so a chained assignment onto an empty selection also fails silently with nothing to observe. - An index that is itself integer-labeled but not a simple
0..n-1range (for example after a prior filter withoutreset_index):df.loc[10:20]uses those labels, not positions, so it can select a completely different set of rows thandf.iloc[10:20]would. - Assigning into a genuinely one-off copy returned by another operation (e.g. a Series pulled out of a
groupbyresult) via chained indexing hits the exact same footgun: the write updates the copy, not any object you can trace back to.
Trade-offs and pitfalls
Copy-on-Write makes the old "is this a view or a copy" ambiguity deterministic (df[cond] is now always a copy), but that determinism does not make chained assignment safe, it just changes how it fails: a warned-and-ineffective write for the single-expression form, and a silent-and-ineffective write for the two-statement form. Both leave df unmodified either way. The reliable pattern is always a single .loc/.iloc call that does the row and column selection together, or an explicit .copy() when you genuinely intend to work on an independent object rather than update the source.
Write Python (pandas) code to compute weekly active users (WAU) from an event log events(user_id, event_time timestamp). Your code should: 1) compute WAU per ISO week, 2) compute week-over-week percentage change, and 3) handle missing days and timezone-aware timestamps. Explain any assumptions.
Sample Answer
Direct answer
Localize event timestamps to a consistent timezone, bucket by ISO week (the ISO 8601 standard week-numbering scheme, weeks run Monday to Sunday and can span a year boundary), count distinct users per week for WAU (weekly active users), then fill any week with zero events before computing week-over-week percent change so a silent gap does not get skipped over.
Approach
- Parse
event_time; if naive, localize it to a chosen timezone (UTC unless you have a reason to use local time); if already timezone-aware, convert to that timezone. - Derive
(iso_year, iso_week)with.dt.isocalendar(), which correctly handles ISO week 52/53 and year-boundary weeks. - Count distinct
user_idper(iso_year, iso_week)for WAU. - Build the full continuous range of ISO weeks between the first and last observed week and left-fill any missing week with
wau = 0, so "no events that week" is visible rather than silently absent from the output. - Compute week-over-week percent change with a
shift(1), explicitly leaving it undefined (notinf) for the first week and for any week following a zero-WAU week.
Worked example
import numpy as np
import pandas as pd
df = pd.DataFrame({
"user_id": [1, 2, 1, 3, 1, 2, 4],
"event_time": [
"2024-01-02 10:00:00", "2024-01-03 11:00:00",
"2024-01-09 09:00:00", "2024-01-10 12:00:00",
"2024-01-25 08:00:00", "2024-01-26 09:30:00", "2024-01-27 14:00:00",
],
})
def compute_wau(df, ts_col="event_time", user_col="user_id", tz="UTC"):
df = df.copy()
df[ts_col] = pd.to_datetime(df[ts_col])
if df[ts_col].dt.tz is None:
df[ts_col] = df[ts_col].dt.tz_localize(tz)
else:
df[ts_col] = df[ts_col].dt.tz_convert(tz)
iso = df[ts_col].dt.isocalendar()
df["iso_year"], df["iso_week"] = iso["year"], iso["week"]
weekly = (df.groupby(["iso_year", "iso_week"])[user_col]
.nunique().rename("wau").reset_index())
start = pd.Timestamp.fromisocalendar(int(weekly["iso_year"].min()), int(weekly["iso_week"].min()), 1)
end = pd.Timestamp.fromisocalendar(int(weekly["iso_year"].max()), int(weekly["iso_week"].max()), 1)
week_starts = pd.date_range(start, end, freq="7D")
all_idx = [(d.isocalendar().year, d.isocalendar().week) for d in week_starts]
full = (pd.DataFrame(all_idx, columns=["iso_year", "iso_week"])
.merge(weekly, on=["iso_year", "iso_week"], how="left")
.fillna({"wau": 0})
.sort_values(["iso_year", "iso_week"])
.reset_index(drop=True))
full["wau_prev"] = full["wau"].shift(1)
with np.errstate(divide="ignore", invalid="ignore"):
full["wow_pct_change"] = ((full["wau"] - full["wau_prev"]) / full["wau_prev"]) * 100
# undefined for the first week and for any week following a zero-WAU
# week (division by zero would otherwise give an unusable inf)
full.loc[(full["wau_prev"].isna()) | (full["wau_prev"] == 0), "wow_pct_change"] = None
return full[["iso_year", "iso_week", "wau", "wow_pct_change"]]
print(compute_wau(df))
Output (verified against pandas 3.0.3):
iso_year iso_week wau wow_pct_change
0 2024 1 2.0 NaN
1 2024 2 2.0 0.0
2 2024 3 0.0 -100.0
3 2024 4 3.0 NaN
Week 3 has zero events (the gap), correctly reported as wau=0 and -100.0% change from week 2's 2. Week 4 follows a zero-WAU week, where a naive percent-change formula would divide by zero and report inf; that case is explicitly nulled out here instead, since "infinite percent growth" is not an interpretable business number.
Assumptions
- WAU is counted per ISO calendar week, not a rolling trailing-7-days window; these are two different (and both legitimate) definitions of "weekly," and the code above computes the calendar-bucket one because the question asks for week-over-week comparison, which implies fixed weeks.
- Naive timestamps are assumed to already be in the target timezone; if they are actually in a mix of timezones (e.g. server local time that changed when infrastructure moved regions), this code will silently mislabel some events' week.
Complexity
O(n) to parse and group the raw events, plus O(w) for the missing-week fill, where w is the number of distinct ISO weeks in range; w is normally tiny compared to n. Memory: the weekly aggregate is O(w), far smaller than the input, since the whole point of the aggregation is to collapse n events down to one row per week.
Edge cases
- Weeks with zero events: made explicit via the fill step rather than silently missing from the output, and handled specially in the percent-change formula (see above).
- ISO week 52/53 and year boundaries:
.dt.isocalendar()returns the ISO year, which can differ from the calendar year for dates near January 1st; grouping by(iso_year, iso_week)rather than(calendar_year, iso_week)is what keeps late-December and early-January weeks from colliding. - Duplicate events for the same user in the same week:
.nunique()onuser_idalready collapses these correctly, no separate deduplication step needed. - Bots or test accounts: not filtered here; if they are present in
user_id, WAU includes them, and a real implementation should exclude them before this step.
Trade-offs and pitfalls
- Silently reporting
inffor a percent change out of a zero base is a common and confusing mistake in growth-metric code; treat it the same way you would treat a first-period-of-history percent change, as undefined rather than a number.
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.