Interview prep
26 pandas interview questions, with answers.
pandas interview questions on indexing, cleaning, groupby, merges, reshaping and performance, including the warnings and silent bugs interviewers love to ask about.
pandas is the daily tool of most data analysts and data scientists, and interviews often include a live pandas exercise. The questions below cover what comes up most: selecting data correctly, cleaning it, grouping and joining it, and keeping it fast.
Many answers include a common mistake. Interviewers often ask follow-ups exactly there, so know why the mistake happens, not just the fix.
These 26 questions are free. SchoolWhool's Foundations of AI course places 650+ interview questions right after the lessons they test, with a mock interview with Gaurav. See also the machine learning interview questions.
Data structures and selection
What's the difference between a Series and a DataFrame?
df['col'] returns a Series; df[['col']] returns a DataFrame.What's the difference between loc and iloc?
loc selects by label and includes the end of a slice; iloc selects by integer position and excludes it. df.loc[df['age'] > 30, 'name'] combines a boolean mask with a column label. Mixing up labels and positions after filtering or sorting, when the index is no longer 0 to n-1, is a classic bug.What is the index for, and when do you reset it?
reset_index(drop=True) gives a clean 0 to n-1 index. set_index is useful for lookups and time series.What is index alignment?
s1 + s2 adds values with the same index label and gives NaN where a label exists in only one. It prevents many errors, but surprises people who expect position-wise addition. Reset the indexes, or use .to_numpy(), when position is what you mean.What is SettingWithCopyWarning, and how do you avoid it?
df[df.a > 0]['b'] = 1, so the original may not change. Use one loc call: df.loc[df.a > 0, 'b'] = 1, or call .copy() when you want an independent subset. With Copy-on-Write, the default from pandas 3.0, chained assignment never modifies the original.How do you filter on several conditions?
&, | and ~, each condition in parentheses: df[(df.a > 1) & (df.b == 'x')]. isin handles membership, and df.query("a > 1 and b == 'x'") can be more readable. Python's and and or don't work on Series.Cleaning and transforming
How do you find and handle missing values?
df.isna().sum(), then decide based on why they're missing: drop rows or columns (dropna with subset or thresh), fill (fillna, forward fill, interpolation for time series) or keep a missing indicator. Filling with a mean computed on the whole dataset before a train/test split leaks information.What's the difference between NaN, None and pd.NA?
NaN is a float, so a missing value turns an integer column into float. None becomes NaN in numeric columns or stays as None in object columns. pd.NA is the missing marker for nullable dtypes like Int64, boolean and string, which let an integer column hold missing values.How and why do you change dtypes?
astype, pd.to_numeric(errors='coerce'), pd.to_datetime and astype('category'). Correct types make operations possible, like date arithmetic, and cut memory; the category dtype can shrink a repetitive string column dramatically. Check df.dtypes right after loading, because numbers stored as text are common.How do you remove duplicate rows?
df.duplicated(subset=[...]).sum(), then drop_duplicates(subset=[...], keep='first'). Decide which columns define a duplicate, usually a business key, rather than comparing every column. keep=False drops every copy, which helps when you want to examine conflicts.apply, map or vectorised operations: which and when?
.str and .dt accessors are fastest. Series.map maps values through a dict or function. apply runs a Python function on each element or row: flexible but slow. For conditional columns, np.where or np.select beats a row-wise apply.How do you work with text columns?
.str accessor: .str.lower(), .str.contains() (a regex by default; pass regex=False for literal text), .str.extract() with capture groups and .str.split(expand=True). The dedicated string dtype makes text columns explicit instead of the catch-all object.How do you work with dates and times?
pd.to_datetime, passing format= for speed and correctness, then use the .dt accessor for parts such as month or weekday. With a DatetimeIndex you can resample('W').sum(), use time-based rolling windows and slice by date strings. Be explicit about time zones with tz_localize and tz_convert.Grouping, merging and reshaping
Explain groupby.
df.groupby('city')['sales'].agg(['sum', 'mean']) is typical. Named aggregation, .agg(total=('sales', 'sum')), gives clean column names.What's the difference between agg, transform and apply on a groupby?
agg reduces each group to one row. transform returns a result the same length as the original, aligned to its rows, so df['share'] = df.sales / df.groupby('city').sales.transform('sum') adds a group statistic as a column. apply is the general, slower fallback.What's the difference between merge, join and concat?
merge is a SQL-style join on columns, with how='inner', 'left', 'right' or 'outer'. join joins on the index. concat stacks objects along rows or columns. merge(..., validate='many_to_one', indicator=True) catches unexpected duplicates and shows where each row came from.Why did the row count grow after a merge?
df_right.key.is_unique before merging, or pass validate='many_to_one' so pandas raises an error instead of quietly multiplying rows. Interviewers ask this because it silently corrupts totals.What do pivot, pivot_table and melt do?
pivot reshapes long data to wide and fails if an index/column pair appears twice. pivot_table aggregates such duplicates with aggfunc, and can add totals with margins=True. melt reshapes wide to long, which is the tidy format most plotting and modelling tools want.What is a MultiIndex?
set_index(['a', 'b']). Select with df.loc[('x', 'y')] or df.xs('x', level='a'), and move levels with stack and unstack. It's powerful but hard to read, so reset_index() before sharing results.How do you compute rolling and cumulative statistics?
rolling(7).mean() gives a moving average (rolling('7D') needs a DatetimeIndex), expanding() and cumsum() give cumulative values. Combine with groupby for per-customer windows. When building model features, shift(1) first so a row never sees its own value or the future.Performance and pitfalls
How do you reduce a DataFrame's memory use?
usecols), specify dtypes, downcast numbers, convert repetitive strings to category and store data as Parquet rather than CSV. df.info(memory_usage='deep') shows the real footprint, including strings.How do you process a file that doesn't fit in memory?
chunksize in read_csv, filtering and aggregating each chunk, and load only the columns you need. Or switch tools: DuckDB can query the file with SQL, and Polars can process it lazily. Converting the file to Parquet once makes later reads much faster.Why is iterrows slow, and what should you use instead?
iterrows builds a new Series for every row inside a Python loop and can change dtypes along the way. Use vectorised operations first; if you really must loop, itertuples is much faster. Needing a loop over rows is usually a sign the operation can be expressed column-wise.What is Copy-on-Write in pandas?
SettingWithCopyWarning and avoids defensive .copy() calls.Should you use inplace=True?
None so it breaks method chaining, and the pandas developers discourage it. Assign the result instead: df = df.dropna().When would you use Polars instead of pandas?
Keep preparing
24 NumPy interview questions
NumPy interview questions on arrays, dtypes, views and copies, broadcasting, vectorisation and linear algebra: the foundations every data science library is built on.
Interview prep23 data visualization interview questions
Data visualization interview questions with answers: choosing the right chart, honest design, matplotlib, seaborn and plotly, and the plots that matter when you build and evaluate models.
Articlepandas loc vs iloc: select by label or by position
loc selects pandas rows and columns by label; iloc selects by integer position. See a side-by-side table, slicing rules, errors and examples you can run.
Interview prep28 scikit-learn interview questions
The scikit-learn questions interviewers actually ask: the estimator API, pipelines and leakage, cross-validation, tuning, and the practical traps that separate people who've used it from people who've read about it.
ArticlePython shallow copy vs deep copy: trace a nested-data bug
Follow a nested dictionary through assignment, shallow copying and deep copying, then choose the right copying boundary for a data workflow.
ArticleLogistic regression from scratch: fit probabilities and inspect errors
Implement stable binary cross entropy and its gradient in NumPy, train on invented data and compare held-out predictions with a constant baseline.
First Principles, the SchoolWhool newsletter
One machine learning idea, explained properly, every week.
The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.
Learn it properly, then the interview is the easy part.
Foundations of AI teaches pandas and the rest of machine learning from first principles, with notebooks that check your work.