Skip to content

Pandas Interview Questions (2026): 18 Questions With Answers, Code and the pandas 3.0 Changes

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 11 min read

PythonpandasPython Interview QuestionsData AnalysisInterview Preparation
Pandas Interview Questions (2026): 18 Questions With Answers, Code and the pandas 3.0 Changes

Pandas interview questions test whether you can load, clean, reshape and summarise tabular data in Python. Expect questions on Series vs DataFrame, selecting with loc and iloc, handling missing values, groupby and aggregation, merging tables, and writing vectorised code instead of loops. In 2026 interviewers also ask about pandas 3.0 (released January 2026), which made a dedicated string dtype the default and made Copy-on-Write the only behaviour, so chained assignment no longer works.

I'm Gulab Chand Tejwani from TechNet Consultancy. Most data analyst interviews I've been part of include at least one live pandas task, usually "here's a small dataset, answer this question". The candidates who do well aren't the ones who know every method. They're the ones who can explain what each line does. The eighteen questions below are written that way, and all the code runs on pandas 3.

Every example uses this small dataset:

import pandas as pd

orders = pd.DataFrame({
    "order_id": [101, 102, 103, 104, 105, 106],
    "customer": ["Asha", "Ravi", "Asha", "Meena", "Ravi", "Kiran"],
    "city": ["Anand", "Vadodara", "Anand", "Surat", None, "Anand"],
    "amount": [1200.0, 450.0, 800.0, None, 300.0, 950.0],
    "order_date": pd.to_datetime([
        "2026-09-02", "2026-09-05", "2026-10-01",
        "2026-10-03", "2026-10-15", "2026-10-20",
    ]),
})

Basics

1. What's the difference between a Series and a DataFrame?

A Series is a one-dimensional labelled array: one column of values with an index. A DataFrame is a two-dimensional table of columns, each of which is a Series sharing the same index. orders["amount"] returns a Series. orders[["amount"]] returns a DataFrame with one column.

2. How do you take a first look at a dataset?

orders.head()        # first 5 rows
orders.shape         # (6, 5)
orders.info()        # columns, dtypes, non-null counts
orders.describe()    # summary statistics for numeric columns
orders.isna().sum()  # missing values per column

Mentioning info() and isna().sum() early shows you check data quality before analysing.

3. What's the difference between loc and iloc?

loc selects by label (index labels and column names). iloc selects by integer position. With loc, slices include the end label. With iloc, they exclude the end position, like normal Python slicing.

orders.loc[0:2, ["customer", "amount"]]   # rows labelled 0, 1, 2
orders.iloc[0:2, [1, 3]]                  # rows at positions 0 and 1

4. How do you filter rows with several conditions?

Use & (and), | (or) and ~ (not), with each condition in brackets. Python's and/or don't work element-wise.

big_anand = orders[(orders["city"] == "Anand") & (orders["amount"] > 900)]
print(big_anand["order_id"].tolist())   # [101, 106]

# query() reads well for longer conditions
orders.query("city == 'Anand' and amount > 900")

Cleaning questions

5. How do you handle missing values?

First decide why they're missing, then choose: drop, fill or flag.

orders["amount"].isna().sum()              # 1
orders.dropna(subset=["amount"])           # drop rows missing amount
orders["city"].fillna("Unknown")           # fill with a label
orders["amount"].fillna(orders["amount"].median())   # fill with the median

A good answer mentions that filling with the mean can distort results when the data is skewed, and that sometimes you keep the missing value and add an is_missing flag column.

6. How do you remove duplicate rows?

orders.drop_duplicates()                               # fully identical rows
orders.drop_duplicates(subset=["customer"], keep="last")   # last order per customer

7. How do you change a column's data type?

orders["order_id"] = orders["order_id"].astype("string")
orders["amount"] = pd.to_numeric(orders["amount"], errors="coerce")   # bad values become NaN

errors="coerce" is the detail interviewers like: it turns unparseable values into missing values instead of crashing.

8. How do you work with dates?

Convert with pd.to_datetime, then use the .dt accessor.

orders["month"] = orders["order_date"].dt.to_period("M")
orders["weekday"] = orders["order_date"].dt.day_name()

Aggregation and reshaping

9. How does groupby work?

Split the data into groups, apply a function to each group, combine the results. Named aggregation keeps output columns readable.

summary = (
    orders.groupby("customer")
    .agg(orders_count=("order_id", "count"), total=("amount", "sum"))
    .sort_values("total", ascending=False)
)
print(summary)

Asha has 2 orders worth 2,000, Kiran 1 order worth 950, Ravi 2 orders worth 750 and Meena 1 order with a missing amount (sum treats it as 0).

pandas groupby as split-apply-combine: split rows by customer, apply sum and count to each group, combine into a summary table
groupby is split, apply, combine. Say that sentence in the interview and then show the code.

10. What's the difference between agg, transform and apply after a groupby?

  • agg returns one row per group (a summary).
  • transform returns a result the same length as the original, aligned to each row. Use it to add a group-level value back to every row.
  • apply runs any function on each group. It's flexible but usually slowest.
orders["customer_total"] = orders.groupby("customer")["amount"].transform("sum")
orders["share_of_customer"] = orders["amount"] / orders["customer_total"]

11. How do you merge two DataFrames?

merge joins on key columns, like SQL joins.

customers = pd.DataFrame({
    "customer": ["Asha", "Ravi", "Meena"],
    "segment": ["Retail", "Wholesale", "Retail"],
})
merged = orders.merge(customers, on="customer", how="left")
print(merged["segment"].isna().sum())   # 1: Kiran isn't in customers

Mention how= (inner, left, right, outer) and checking row counts before and after. If a left join adds rows, the right table has duplicate keys. validate="many_to_one" makes pandas raise an error in that case.

MethodWhat it doesSQL equivalent
mergeJoins on columns (or index)JOIN ... ON
joinJoins on the index by defaultJOIN on a key that is the index
concatStacks frames vertically or side by sideUNION ALL (axis=0)
merge, join and concat

12. What's the difference between pivot and pivot_table?

pivot reshapes without aggregating and fails if index/column pairs repeat. pivot_table aggregates duplicates (mean by default) and handles them.

orders.pivot_table(index="city", columns="month", values="amount", aggfunc="sum", fill_value=0)

13. How do you go from wide to long format?

melt turns columns into rows, which you'll need before plotting or loading into a BI tool.

wide = pd.DataFrame({"product": ["A", "B"], "Sep": [10, 7], "Oct": [12, 9]})
long = wide.melt(id_vars="product", var_name="month", value_name="units")

Performance and pandas 3.0 questions

14. Why should you avoid looping over rows?

Row loops (iterrows, Python for loops) run one row at a time in Python. Vectorised operations run in optimised compiled code on whole columns at once, often orders of magnitude faster on large data.

# slow
# for i, row in orders.iterrows(): ...

# fast
orders["amount_with_tax"] = orders["amount"] * 1.18

15. How do you create a column based on conditions without apply?

Use np.where for two outcomes, np.select for several.

import numpy as np

orders["size"] = np.select(
    [orders["amount"] >= 1000, orders["amount"] >= 500],
    ["large", "medium"],
    default="small",
)

Note that rows with a missing amount fall to the default here. Say that out loud if it matters for the question.

16. What changed in pandas 3.0?

pandas 3.0.0 was released on 21 January 2026. The changes interviewers ask about:

  • String dtype by default. Text columns are now inferred as the dedicated str dtype instead of object. Code that checks dtype == object for text may break.
  • Copy-on-Write always. Any subset or derived DataFrame behaves as a copy. The mode.copy_on_write option no longer has any effect.
  • Chained assignment stops working. Something like df[df["a"] > 0]["b"] = 1 doesn't modify df. SettingWithCopyWarning is gone, and pandas warns with a ChainedAssignmentError instead. Use .loc in one step.
  • pd.col() gives a new way to refer to columns in expressions, such as df.assign(c=pd.col("a") + pd.col("b")).
  • pandas 3.0 needs Python 3.11 or newer.
print(orders["customer"].dtype)   # str on pandas 3

# Correct way to update a subset in pandas 3
orders.loc[orders["city"].isna(), "city"] = "Unknown"
pandas 3.0 changes: str dtype by default, Copy-on-Write always on, chained assignment no longer works, pd.col expressions, Python 3.11 or newer
The pandas 3.0 changes most likely to come up, from the official release notes.

17. What is SettingWithCopyWarning, and why don't you see it any more?

In pandas 2 and earlier, chained assignment could either change the original DataFrame or a temporary copy, and pandas warned you because it couldn't tell which. With Copy-on-Write in pandas 3, chained assignment never changes the original, so that warning was removed. Try it anyway and pandas 3 shows a ChainedAssignmentError warning pointing you to .loc. The habit that works in every version: select and assign in one .loc call.

18. How would you read a file that's too large for memory?

totals = {}
for chunk in pd.read_csv("big_sales.csv", chunksize=100_000, usecols=["city", "amount"]):
    for city, amt in chunk.groupby("city")["amount"].sum().items():
        totals[city] = totals.get(city, 0) + amt

Also mention loading only needed columns (usecols), choosing smaller dtypes, and columnar formats like Parquet. For very large data, tools such as DuckDB or Polars are worth naming, while saying you'd pick based on the team's stack.

Practice questions

Question 1pandas · Selection

df has a default integer index 0 to 9. How many rows do df.loc[2:5] and df.iloc[2:5] return?

  1. A4 and 4
  2. B4 and 3
  3. C3 and 3
  4. D3 and 4
Show answer and explanation

Correct answer: B

loc includes the end label (2, 3, 4, 5 = 4 rows). iloc excludes the end position (2, 3, 4 = 3 rows).

Question 2pandas · groupby

You want to add a column showing each order's share of its customer's total spend, keeping one row per order. Which method fits?

  1. Agroupby().agg()
  2. Bgroupby().apply() returning one value per group
  3. Cgroupby()[col].transform('sum')
  4. Dpivot_table()
Show answer and explanation

Correct answer: C

transform returns a result aligned to the original rows, so you can divide each order's amount by its customer total. agg collapses to one row per customer.

Question 3pandas · pandas 3.0

On pandas 3, a teammate writes df[df['score'] < 0]['score'] = 0 and is surprised nothing changes. What's the fix?

  1. Adf.loc[df['score'] < 0, 'score'] = 0
  2. BAdd .copy() before the assignment
  3. CTurn on mode.copy_on_write
  4. DUse inplace=True
Show answer and explanation

Correct answer: A

Chained assignment doesn't modify the original under Copy-on-Write, which is always on in pandas 3. A single .loc call with the row condition and the column does.

Question 4pandas · Merge

orders has 1,000 rows. After orders.merge(customers, on='customer_id', how='left') you get 1,040 rows. What's the most likely reason?

  1. ASome orders have no matching customer
  2. BThe merge used an inner join by mistake
  3. Ccustomer_id has missing values in orders
  4. Dcustomers has duplicate customer_id values
Show answer and explanation

Correct answer: D

A left join keeps every left row once per match. Duplicate keys on the right multiply rows. Unmatched orders (A) would keep the count at 1,000 with missing values. Check with customers["customer_id"].duplicated().sum() or use validate="many_to_one".

How should you prepare for a pandas interview?

Pick two public datasets and answer ten questions on each with pandas: top customers, monthly trend, share of total, missing data, a join with a lookup table. Time yourself, then rewrite anything that uses a loop. Practise explaining each step out loud, because live rounds grade your reasoning as much as the output.

For structured practice, Python interview practice has 200+ coding questions you run in a browser editor with pandas and NumPy available, including a data analyst track, with hints, test checks and worked answers, for a one-time ₹199. Analyst interviews nearly always include SQL as well, and the SQL interview practice store has a free ShopX company set to start with (other companies are ₹99 each or ₹699 for the bundle, 30 days of access).

If you're starting out, the data analyst roadmap for 2026 shows where pandas fits alongside Excel, SQL and Power BI.

FAQ

What pandas questions are asked in data analyst interviews?

Usually loc vs iloc, filtering, handling missing values, groupby with aggregation, merge, pivot tables and date handling, plus a short live task on a small dataset.

What is the difference between loc and iloc in pandas?

loc selects by labels (index labels and column names) and includes the end of a slice. iloc selects by integer position and excludes the end, like standard Python slicing.

What changed in pandas 3.0?

Released in January 2026, pandas 3.0 makes the str dtype the default for text, makes Copy-on-Write the only behaviour (so chained assignment no longer modifies data), replaces SettingWithCopyWarning with a ChainedAssignmentError warning, adds pd.col() expressions, and requires Python 3.11 or newer.

Should I learn pandas or SQL first?

For analyst roles, most people learn SQL first because almost every job uses it, then pandas for cleaning and analysis that's awkward in SQL. Both come up in interviews.

Is pandas still worth learning with Polars and DuckDB around?

Yes. pandas is still the most widely used Python data library and the one most interviews test. Knowing that Polars and DuckDB exist, and when they help, is a bonus.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.