Pandas Interview Questions

Dan Lee's profile image
Dan LeeData & AI Lead
Last update
Pandas Interview Questions

Pandas interviews rarely ask you to recite the API. They hand you a DataFrame that behaves oddly, a join that returned too many rows or a report that takes ten minutes, and they watch how you reason about it. The questions that separate candidates cluster in a few places: how the index drives alignment, what groupby returns, how merges multiply rows and how dtypes decide memory and missing values.

Many slips come from habits formed on older pandas. Since pandas 3.0 shipped in January 2026, Copy-on-Write is always on, chained assignment never updates the original frame, text columns default to a new str dtype and parsed datetimes default to microsecond resolution. Code that passed review in 2024 can now produce wrong numbers with nothing more than a warning, and interviewers who use pandas daily know it.

The 30 questions below are grouped into five areas, each with a short note on what interviewers look for. Every solution gives the answer, the reason and the trap, with code where code is the clearest proof. Examples target pandas 3.x (3.1 is the current release as of October 2026). After the questions you will find a prep plan, a short self-check quiz and answers to common questions.

Intermediate30 questions

Pandas Interview Questions

Practice questions on the pandas skills interviews test most: indexing and alignment, Copy-on-Write, groupby, merges, reshaping, dtypes, time series and performance, updated for pandas 3.

Data ScientistData AnalystData EngineerMachine Learning EngineerQuantitative AnalystAnalytics Engineer

Indexing, Alignment and MultiIndex

Interviewers start here because most silent pandas bugs trace back to the index. Arithmetic, column assignment and comparisons all line rows up by label before they touch a value, so a sort, filter or reset in the wrong place changes results without raising anything.

Hold onto one idea: loc works on labels, iloc works on positions, and every operation between two pandas objects aligns on labels first. If you can predict what the index looks like after each step, most questions in this group answer themselves.

Indexing, Alignment and MultiIndex

A teammate filters a DataFrame to rows where country == "US", then writes us.loc[0:2] expecting the first three US rows. They get two rows. Explain what happened and how to select the first three.

EasyIndexing, Alignment and MultiIndex

Sample Answer

Filtering keeps the original row labels, so the US rows here are labelled 0, 2 and 4. loc selects by label and its slices include both endpoints, so us.loc[0:2] returns every surviving label between 0 and 2: rows 0 and 2. iloc selects by position and excludes the stop, like a Python slice, so us.iloc[0:3] returns the first three rows whatever their labels. us.head(3) does the same. The trap is treating an integer index as positions. Once the index has gaps, labels and positions diverge, and reset_index(drop=True) is the explicit way to renumber when you really want 0 to n-1.

Python
1import pandas as pd
2
3df = pd.DataFrame({"country": ["US", "CA", "US", "MX", "US"], "v": [1, 2, 3, 4, 5]})
4us = df[df["country"] == "US"]                  # labels 0, 2, 4
5print(us.loc[0:2].index.tolist())               # [0, 2]: labels 0..2, inclusive
6print(us.iloc[0:3].index.tolist())              # [0, 2, 4]: first three positions
7print(us.reset_index(drop=True).loc[0:2].index.tolist())  # [0, 1, 2]
Learn this in the Pandas course

Copy-on-Write and Safe Updates

This area changed more than any other in recent pandas, which is why interviewers bring it up. Since pandas 3.0 (January 2026), Copy-on-Write is the only mode: any DataFrame or Series derived from another behaves as an independent copy, and the SettingWithCopyWarning many people learned to silence is gone.

The rule that matters: a write lands on the object you index directly, in one step. df.loc[mask, "col"] = value updates df. Anything that indexes twice before assigning updates a temporary object, and pandas tells you with a ChainedAssignmentError warning rather than an exception.

Copy-on-Write and Safe Updates

On pandas 3.x this line runs, prints a warning, and the DataFrame is unchanged: df[df["status"] == "test"]["revenue"] = 0. Why, and what is the fix?

EasyCopy-on-Write and Safe Updates

Sample Answer

The first [...] builds a new DataFrame from the boolean mask. Under Copy-on-Write that result behaves as a copy, so the second [...] = 0 writes into a temporary that is immediately thrown away. pandas detects the pattern and emits ChainedAssignmentError, which is a Warning subclass, so the script keeps running with the old values. The fix is one indexing call that names rows and columns together: df.loc[df["status"] == "test", "revenue"] = 0. The same rule covers df["revenue"][0] = 0, which also never updates df now. Before 3.0 the second form sometimes worked, depending on whether pandas happened to return a view, and that unpredictability is what CoW removed.

Python
1import pandas as pd
2
3df = pd.DataFrame({"status": ["live", "test", "test"], "revenue": [10, 20, 30]})
4df[df["status"] == "test"]["revenue"] = 0        # ChainedAssignmentError warning
5print(df["revenue"].tolist())                     # [10, 20, 30], unchanged
6df.loc[df["status"] == "test", "revenue"] = 0     # one step, updates df
7print(df["revenue"].tolist())                     # [10, 0, 0]
Learn this in the Pandas course

GroupBy, Windows and Time Series

Most analytics take-homes come down to group, aggregate and compare over time. Interviewers watch whether you know which groupby method keeps the row count, which collapses it, and when you have fallen back to a slow Python loop wearing an apply costume.

The key idea: agg returns one row per group, transform returns one value per original row aligned to the input index, and apply is the general escape hatch you reach for last. Time adds one more rule. A window defined by time ("7D") and a window defined by row count (7) give different answers as soon as days are missing.

GroupBy, Windows and Time Series

Build a per-user report with total revenue, number of orders and average order value, with flat column names ready to export.

EasyGroupBy, Windows and Time Series

Sample Answer

Named aggregation passes new_name=(column, function) pairs to agg and returns flat, readable columns in one pass. Built-in names like "sum" and "mean" run on optimized compiled paths, while a lambda such as lambda s: s.sum() gives the same answer far more slowly when there are many groups. Watch "size" versus "count": size counts rows including NaN, count counts non-null values, and mixing them up is a common source of order counts that don't reconcile. Add .reset_index() when the next step is a merge or a CSV. The older dict-of-lists style produces a two-level column index that you then have to flatten by hand.

Python
1import pandas as pd
2
3df = pd.DataFrame({"user": ["u1", "u1", "u2", "u2", "u2"], "rev": [5, 7, 3, 4, 10]})
4report = (df.groupby("user")
5            .agg(total=("rev", "sum"), orders=("rev", "size"), aov=("rev", "mean"))
6            .reset_index())
7print(report)   # u1: 12, 2, 6.0   u2: 17, 3, 5.67
Learn this in the Pandas course

Merges, Joins and Reshaping

Joins are where analysis numbers go wrong at scale. A merge on a key you assumed was unique multiplies rows, totals inflate, and nothing errors. Interviewers ask about merges because they want to see you check cardinality before you trust a result.

The habit that matters: state the expected relationship (one-to-one, many-to-one) and make pandas enforce it with validate=, then confirm coverage with indicator=True. Reshaping questions test the same discipline, because pivot refuses duplicate keys while pivot_table quietly aggregates them.

Merges, Joins and Reshaping

orders has 1,000,000 rows. After orders.merge(customers, on="customer_id", how="left") you have 1,084,512 rows and revenue is 9% too high. Diagnose it and prevent it from happening again.

MediumMerges, Joins and Reshaping

Sample Answer

A merge returns one output row per matching pair, so a customer_id that appears k times in customers copies each of its orders k times. Some customers have duplicate rows, perhaps from a history table or a double load. Find them with customers["customer_id"].duplicated(keep=False), decide which row is correct (latest updated_at, say) and dedupe before merging. Then lock the expectation in with validate="many_to_one", which raises MergeError when the right-side keys are not unique. Also assert that a left join you expect to preserve rows still has len(orders) rows. The trap is calling drop_duplicates() on the merged output, which hides the symptom and can delete legitimate repeat orders.

Python
1import pandas as pd
2
3orders = pd.DataFrame({"customer_id": [1, 1, 2], "amount": [10, 20, 30]})
4customers = pd.DataFrame({"customer_id": [1, 1, 2], "tier": ["gold", "gold", "basic"]})
5print(len(orders.merge(customers, on="customer_id")))   # 5 rows, not 3
6try:
7    orders.merge(customers, on="customer_id", how="left", validate="many_to_one")
8except pd.errors.MergeError as e:
9    print("MergeError:", str(e).splitlines()[0])
Learn this in the Pandas course

Dtypes, Missing Data and Performance

Dtypes decide three things interviewers care about: whether values survive a load intact, how missing data behaves in arithmetic, and how much memory a frame takes. pandas 3 moved the defaults here too, with a dedicated str dtype for text and microsecond datetimes.

The idea that ties this area together: pandas is fast when the work stays in typed columns and compiled code, and slow when it drops to one Python object per value. Row-wise apply, object columns and Python loops are the usual suspects when a job runs out of time or memory.

Dtypes, Missing Data and Performance

A column of integer IDs read from CSV comes back as float64, and an ID like 1234567890123456789 changes value. Why, and how do you keep IDs exact?

EasyDtypes, Missing Data and Performance

Sample Answer

NumPy's int64 has no missing value, so a single empty cell makes pandas store the column as float64 with NaN. A float64 has a 53-bit mantissa, so integers above 2^53 (about 9.007e15) cannot all be represented, and large IDs silently round. Use the nullable Int64 dtype (capital I), which keeps a separate mask and shows missing as pd.NA: pass dtype={"id": "Int64"} to read_csv, or dtype_backend="numpy_nullable" for the whole file. dtype_backend="pyarrow" gives int64[pyarrow] with the same behavior. If the column is an identifier you never do arithmetic on, reading it as a string is the safest choice of all.

Python
1import io
2import pandas as pd
3
4csv = "id,x\n1234567890123456789,1\n,2\n"
5print(pd.read_csv(io.StringIO(csv))["id"].tolist())          # [1.2345678901234568e+18, nan]
6print(pd.read_csv(io.StringIO(csv), dtype={"id": "Int64"})["id"].tolist())
7# [1234567890123456789, <NA>]
Learn this in the Pandas course

How to Prepare for Pandas Interviews

Predict the index after every step

Before running a line, say out loud what the index will look like afterwards. Filters keep old labels, reset_index renumbers, groupby moves keys into the index and explode repeats labels. Practise label versus position selection in Select rows with loc and iloc until loc slices including their endpoint feels obvious.

Write every update as one indexing call

Under pandas 3, df.loc[rows, cols] = value is the only update pattern you need. Rewrite any chained assignment or inplace=True on a column the moment you see it, and say why in the interview. Update values safely drills this, and Mutability traps covers the Python reference rules underneath it.

Check cardinality before trusting a join

Make three checks a reflex: duplicated() on the key you expect to be unique, validate= on the merge and indicator=True to measure coverage. Print row counts before and after. Keep matches or keep every search and Join on multiple keys walk through both failure modes on real-looking data.

Know agg, transform and filter cold

Most groupby prompts are one of three shapes: one row per group (agg), one value per original row (transform) or keep whole groups that pass a test (filter). Name the shape before writing code. Practise named aggregation in Build multi-metric reports and row-level context in Add group context to rows.

Practise time windows on irregular data

Build a small event table with missing days and compare rolling(7), rolling("7D") and resample("W") by hand. Then check the dtype of every parsed timestamp, since pandas 3 defaults to microseconds. Calculate rolling metrics and Build daily and weekly reports cover both window styles.

How Ready Are You for Pandas Interviews?

1 / 6
Indexing

After filtering a DataFrame, df.loc[0:2] returns two rows instead of three. What is the best explanation?

Frequently Asked Questions

Is pandas asked in data science interviews?

Yes, often. Many data science and analytics loops include a live coding round in Python where pandas is the expected tool, and take-home assignments almost always arrive as CSV files. Interviewers look for clean groupby and merge logic, awareness of missing data and the ability to explain why a number is right. SQL rounds cover similar ground, so practising both on the same problems is efficient.

Which pandas version should I prepare for?

Prepare for pandas 3.x. Version 3.0 shipped in January 2026 and 3.1 is current as of October 2026. The changes most likely to come up are Copy-on-Write as the only mode, the str dtype for text, microsecond datetime resolution and observed=True as the groupby default. Interviewers may still run 2.x, so knowing what changed and why is a strong signal either way.

How long does it take to prepare for a pandas interview?

If you already use pandas at work, one to two weeks of focused practice is usually enough: an hour a day on selection, groupby, merges, reshaping and time series, plus a few timed mixed problems. Starting from basic Python, plan on four to six weeks. The fastest gains come from writing code without autocomplete and explaining each step aloud.

Should I use pandas or SQL in a live coding interview?

Use what the interviewer asks for, and if you get a choice, use the one you can write correctly fastest. pandas shines for multi-step transformations, time series and quick checks on intermediate results. SQL reads more clearly for set-based joins and aggregations. Many candidates sketch the logic in SQL terms, then implement it in pandas, which is a reasonable way to show structured thinking.

Do I need to know Polars or PySpark as well?

Not for most pandas interviews, but it helps to know where pandas stops. Single-machine pandas handles a few gigabytes comfortably with good dtypes. Beyond that, interviewers expect you to mention Parquet, chunked processing, Polars or Spark. You do not need their APIs memorized; being able to say why a lazy or distributed engine fits a larger job is usually enough.

What level of pandas do I need for a data analyst role?

Analyst interviews expect fluent filtering, sorting, groupby with named aggregation, merges with the right join type, pivot tables and basic date handling. You should be able to spot a row explosion after a join and explain missing values in a result. Copy-on-Write details, MultiIndex slicing and memory tuning appear more often in data scientist and data engineer loops.

Dan Lee's profile image

Written by

Dan Lee

Data & AI Lead

Dan is a seasoned data scientist and ML coach with 10+ years of experience at Google, PayPal, and startups. He has helped candidates land top-paying roles and offers personalized guidance to accelerate your data career.

Connect on LinkedIn