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?
A Series is a one-dimensional labelled array with an index. A DataFrame is a two-dimensional table whose columns are Series sharing the same row index, and each column can have its own dtype. Selecting one column with 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?
The index labels rows and drives alignment and fast lookups. After filtering, sorting or concatenating, it may have gaps or duplicates; 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?
Arithmetic between Series or DataFrames matches rows by label, not position: 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?
It warns that you may be assigning to a temporary copy, typically through chained indexing like 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?
Combine boolean masks with &, | 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?
Count them with 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?
Use 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?
Inspect with 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?
Vectorised operations and the .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?
Use the .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?
Parse with 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.
It's split-apply-combine: split rows into groups by one or more keys, apply an aggregation, transformation or filter to each group, and combine the results. 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?
The key has duplicates on the right side, so each left row matched several right rows. Check 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?
A hierarchical index with several levels, created by grouping on multiple keys or 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?
Read only the columns you need (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?
Read it in pieces with 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?
With Copy-on-Write (opt-in in pandas 2.x, the default in 3.0), any DataFrame derived from another behaves as a copy, but the data is only copied when one of them is modified. It removes the ambiguity behind SettingWithCopyWarning and avoids defensive .copy() calls.
Should you use inplace=True?
Usually not. It rarely saves memory, returns 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?
Polars is a DataFrame library written in Rust, multi-threaded with a lazy query optimiser, and often much faster and lighter on large data. pandas has the bigger ecosystem and integrates with nearly every plotting and modelling library. A good answer: pandas by default, Polars or DuckDB when data size or speed becomes the bottleneck.

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.