Pandas and NumPy interview questions and answers

Pandas interview questions check whether you can shape real data quickly and correctly: select with loc and iloc, aggregate with groupby, combine tables with merge, reshape with pivot and melt, and handle missing values without silent mistakes. NumPy interview questions usually come in the same round and focus on arrays, broadcasting, vectorization and the difference between a view and a copy. Most of the score comes from live tasks in a notebook, where clean, vectorized code and a check on the result beat a clever one-liner.

By Published 9 min read

How pandas and NumPy show up in interviews

Pandas is the default tool for tabular data in Python, so it appears in interviews for data analysts, data scientists, data engineers, ML engineers and Python backend roles that touch reporting. Some teams ask concept questions, but most hand you a small dataset and a task: clean it, aggregate it, join it to another table and answer a business question. NumPy questions tend to come from ML and scientific computing teams, and from interviewers who want to know whether you understand what pandas is doing underneath.

  1. Warm-up conceptsShort questions on the DataFrame model, indexing, dtypes and missing values, often while you open the data.
  2. Live data taskOften around half an hour in a notebook or shared editor. You load a CSV, fix types, filter, group, merge and report a number or a small table.
  3. Follow-ups on scaleWhat happens with ten million rows, why your apply is slow, how much memory the frame uses and how you would cut it.
  4. Take-home variantSome teams send a dataset and a few questions instead. Readable steps, checked assumptions and a short write-up matter as much as the answers.

Pandas fundamentals questions

Basics for freshers and the opening minutes of any data round
QuestionWhat it testsWhat a strong answer shows
What is the difference between a Series and a DataFrame?Data modelA Series is one labeled column of values with an index. A DataFrame is a table of Series that share the same row index, each column with its own dtype.
What is the index for, and when would you reset it?LabelsThe index labels rows and drives alignment in arithmetic, joins and plots. Reset it after a filter or groupby when you want a plain column back or a clean 0 to n-1 range.
loc versus iloc?Selectionloc selects by label and its slices include the end label. iloc selects by integer position and its slices exclude the end, like Python lists.
How do you filter rows on two conditions?Boolean masksCombine masks with & and |, wrap each condition in parentheses, and use ~ for not. Python's and and or raise an error on a Series.
What do info(), describe() and value_counts() tell you first?Data checksColumn types and null counts, numeric spread and outliers, and the distribution of categories. A strong candidate runs them before writing any logic.
What does axis=0 versus axis=1 mean?Orientationaxis=0 works down the rows, so a sum gives one value per column. axis=1 works across columns, giving one value per row.
How does pandas represent missing values?NullsTraditionally NaN for floats, NaT for datetimes and None or NaN in object columns. Newer nullable dtypes use pd.NA. isna() catches all of them; comparing with == np.nan never does.
Why might an integer column turn into floats after a merge?DtypesA left join that finds no match fills NaN, and the classic int64 dtype cannot hold it, so the column is upcast to float. The nullable Int64 dtype keeps integers.
What is the difference between drop_duplicates and duplicated?Cleaningduplicated returns a boolean mask; drop_duplicates removes rows. Both take subset and keep, which decides which copy survives.
How do you parse dates when reading a file?I/OUse parse_dates in read_csv or pd.to_datetime afterwards, with an explicit format when you know it. Then the .dt accessor gives year, weekday and so on.
Basics for freshers and the opening minutes of any data round. Scroll sideways on a small screen.

NumPy interview questions

NumPy questions test whether you think in whole arrays. An ndarray holds one dtype in a contiguous block of memory, which is why vectorized operations run in compiled loops instead of Python ones. Expect questions on shapes and axes, broadcasting, fancy indexing and when you get a view rather than a copy.

import numpy as np

a = np.arange(6).reshape(2, 3)      # [[0 1 2]
                                    #  [3 4 5]]
col_means = a.mean(axis=0)          # shape (3,): mean of each column
centered = a - col_means            # (2, 3) minus (3,) broadcasts across rows
print(centered.tolist())            # [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]]

row_max = a.max(axis=1, keepdims=True)   # shape (2, 1)
print((a / row_max).round(2).tolist())   # [[0.0, 0.5, 1.0], [0.6, 0.8, 1.0]]

view = a[:, 1]          # basic slice: a view on the same memory
view[0] = 99
print(a[0, 1])          # 99, the original changed

picked = a[[0, 1], [0, 0]]   # fancy indexing: always a copy
picked[0] = -1
print(a[0, 0])               # 0, the original did not change
print(np.shares_memory(a, view), np.shares_memory(a, picked))  # True False
Broadcasting and views versus copies, with the printed results as comments.
  • Why is a NumPy array faster than a Python list for math? One dtype in contiguous memory, so operations run in compiled loops without boxing each number as a Python object. A list stores pointers to separate objects.
  • State the broadcasting rule. Compare shapes from the last dimension backwards. Two dimensions are compatible when they are equal or one of them is 1. Missing leading dimensions count as 1. Otherwise NumPy raises an error.
  • When does slicing give a view and when a copy? Basic slices and reshapes usually return views on the same buffer. Fancy indexing with lists or boolean masks returns a copy. np.shares_memory settles it when you are unsure.
  • What does `reshape(-1, 1)` do? Turns a flat array into a single column and lets NumPy work out the row count. scikit-learn expects that 2D shape for a single feature.
  • How do you replace values conditionally without a loop? np.where(cond, a, b) for two branches, np.select for several, or a boolean mask assignment such as arr[arr < 0] = 0.
  • Why does `np.nan == np.nan` return False? NaN is defined as unequal to everything, itself included. Use np.isnan, or np.nanmean and friends to skip missing values.
  • How do you make random results reproducible? Create a generator with np.random.default_rng(seed) and pass it around, rather than relying on the older global seed.
  • **What is the difference between np.dot, @ and *?** * multiplies element by element. @ (and np.matmul) is matrix multiplication. np.dot matches @ for 2D arrays but behaves differently for higher dimensions.

Groupby, merge and reshaping questions

This is where most live tasks are won or lost. Interviewers watch whether you choose the right join, keep row counts under control, and reach for transform when the result must line up with the original rows.

import pandas as pd

orders = pd.DataFrame({
    "order_id": [1, 2, 3, 4, 5, 6],
    "region": ["east", "east", "west", "west", "west", "east"],
    "product": ["A", "B", "A", "C", "C", "A"],
    "qty": [3, 1, 2, 5, 1, 4],
})
prices = pd.DataFrame({"product": ["A", "B", "C"], "unit_price": [10, 25, 8]})

# validate= fails loudly if prices has duplicate products (a silent row blow-up otherwise)
df = orders.merge(prices, on="product", how="left", validate="many_to_one")
df["revenue"] = df["qty"] * df["unit_price"]

# Named aggregation: one row per region and product
by_product = (
    df.groupby(["region", "product"], as_index=False)
      .agg(revenue=("revenue", "sum"), orders=("order_id", "count"))
)

# Top 2 products per region by revenue
top2 = (
    by_product.sort_values(["region", "revenue"], ascending=[True, False])
              .groupby("region")
              .head(2)
)
print(top2.to_string(index=False))
# region product  revenue  orders
#   east       A       70       2
#   east       B       25       1
#   west       C       48       2
#   west       A       20       1

# transform keeps the original shape: each order's share of its region's revenue
df["region_share"] = df["revenue"] / df.groupby("region")["revenue"].transform("sum")
Merge with a safety check, named aggregation, top N per group, and a per-row share with transform.
Intermediate questions on combining and reshaping
QuestionWhat it testsWhat a strong answer shows
agg versus transform versus apply after a groupby?Groupby modelagg returns one row per group. transform returns a result the same length as the input, aligned to the original rows. apply is the flexible fallback and the slowest.
Your merge returned more rows than the left table. Why?Join cardinalityThe right key is not unique, so each left row matched several. Check with duplicated on the key, and pass validate="many_to_one" to catch it next time.
merge, join or concat?Combiningmerge joins on columns or indexes like SQL. join is a shortcut that joins on the index. concat stacks frames along an axis without matching keys.
How do you find rows in one table that are missing from another?Anti-joinLeft merge with indicator=True and keep rows where _merge == "left_only", or use ~df.key.isin(other.key) for a single key.
pivot versus pivot_table?Reshapingpivot only reshapes and fails on duplicate index and column pairs. pivot_table aggregates duplicates with a function such as sum or mean and can add margins.
When would you use melt?Wide to longTo turn one column per month or per metric into rows of id, variable and value, which is the shape groupby, plotting libraries and databases prefer.
What do stack and unstack do?MultiIndexThey move a level between the row index and the columns. unstack after a two-key groupby gives a quick cross table.
How do you compute a 7-day rolling average per user?WindowsSort by user and date, then df.groupby("user").rolling("7D", on="date")["value"].mean(). A time-based window counts calendar days, so say whether missing dates should count as zero or simply be absent.
How do you turn daily data into weekly totals?Time seriesSet a datetime index and call resample("W").sum(), or group with pd.Grouper(freq="W") when other keys are involved. Say which day the week ends on.
How do you split a column of lists into rows?explodedf.explode("tags") repeats the other columns for each element. Reset the index afterwards if you need unique row labels.
Intermediate questions on combining and reshaping. Scroll sideways on a small screen.

Missing data and cleaning questions

  • How do you decide between dropping and filling missing values? Look at how many are missing, whether the gaps are random, and what the column feeds. Dropping a few random rows is fine; filling a target or a key field usually is not.
  • How do you fill missing values with each group's median? df["x"] = df["x"].fillna(df.groupby("g")["x"].transform("median")). The transform keeps the medians aligned with the original rows.
  • What is the difference between `ffill` and `interpolate`? Forward fill copies the last known value, which suits states and prices. Interpolation estimates values between known points, which suits smooth sensor readings.
  • How do you keep only the latest record per customer? Sort by the timestamp, then drop_duplicates("customer_id", keep="last"), or use idxmax on the timestamp within a groupby.
  • A numeric column came in as text. What happened? Some values are not numbers: a word such as "unknown", a unit, a currency sign or a thousands separator. Common markers such as "N/A" and empty cells are already read as missing by default. The column shows as object, or as a string dtype in newer pandas; pd.to_numeric(errors="coerce") turns the bad values into NaN so you can inspect what failed.

Performance, memory and copy-on-write questions

Senior and experienced-level questions
QuestionWhat it testsWhat a strong answer shows
Why is df.apply(func, axis=1) slow, and what do you use instead?VectorizationIt calls a Python function once per row. Column arithmetic, np.where, np.select, .str and .dt methods, map with a dict, or a merge usually do the same work in compiled code.
iterrows or itertuples, if you must loop?Loopingitertuples is much faster and keeps dtypes; iterrows builds a Series per row and can change types. Better still, avoid the loop.
How do you cut a DataFrame's memory use?DtypesMeasure with memory_usage(deep=True), convert repeated strings to category, downcast numeric columns, and read only the columns you need with usecols.
The CSV is larger than memory. What are your options?ScaleRead in chunks with chunksize and aggregate as you go, read only needed columns, switch to a columnar format such as Parquet, or move the work to a database or an out-of-core engine.
What is SettingWithCopyWarning?Chained assignmentIt warned that an assignment such as df[df.a > 1]["b"] = 0 might hit a temporary copy and leave the original unchanged. The fix is one .loc call: df.loc[df.a > 1, "b"] = 0.
What is copy-on-write in pandas?Version awarenessAny object derived from another behaves as its own copy, and data is only copied when one of them is modified. It became the default in pandas 3.0, so chained assignment never updates the original and the old warning goes away. Say which version your team runs.
When do you call .copy() explicitly?OwnershipWhen you take a subset that you plan to modify as a separate table. It states intent and behaves the same on older and newer pandas versions.
Why avoid inplace=True?StyleIt rarely saves memory, breaks method chaining and returns None, which causes bugs like df = df.dropna(inplace=True). Reassigning is clearer.
Senior and experienced-level questions. Scroll sideways on a small screen.

Fictional example

A live task: "Which two products earn the most in each region?"
Interviewer
You have an orders table and a price list. Give me the top two products by revenue in each region.
Candidate
First I will check the price list for duplicate products, since a duplicate would multiply rows in the join. I will merge with how="left" and validate="many_to_one", then check that the row count matches the orders table and that no unit price came back null. Revenue is qty times unit price. Then I group by region and product with a named aggregation, sort by region and revenue descending, and take head(2) per region. For ties I would ask whether you want both products or a stable tie-break, because head simply keeps the first rows in sort order.
Interviewer
And if the orders table had fifty million rows?
Candidate
I would read only the four columns I need, make region and product categories, and aggregate in chunks before merging prices onto the much smaller grouped result. If it keeps growing, this is a GROUP BY that belongs in the warehouse rather than in a notebook.

Scenario questions to practice

  • Find each user's first and last purchase date and the days between them. Tests groupby with min and max on datetimes and timedelta arithmetic.
  • Flag sessions: a new session starts after 30 minutes of inactivity. Tests sorting, diff within groups, a boolean flag and cumsum to number sessions.
  • Compare this month's sales with last month's per product. Tests pivot_table, shift or pct_change, and handling products that appear in only one month.
  • Two exports of the same table disagree. Show the differences. Tests an outer merge with indicator=True, plus comparing columns for rows present in both.

A one-week pandas and NumPy practice plan

  • Day 1: load a public dataset and narrate your first five checks out loud: shape, dtypes, nulls, duplicates and value counts.
  • Day 2: write ten selections with loc, iloc and boolean masks, then redo two that you first wrote with chained indexing.
  • Day 3: practice groupby with agg, transform and a top N per group until you can write each without looking anything up.
  • Day 4: merge two tables five ways, predict the row count before each merge, and use validate and indicator.
  • Day 5: reshape with pivot_table, melt and resample; build a weekly report from daily rows.
  • Day 6: NumPy: broadcasting drills, views versus copies, and rewriting one apply as vectorized code, timing both.
  • Day 7: a timed mock: one 30-minute task, then explain your choices in three minutes.

Pandas rounds usually sit inside larger loops, so read data analyst interview questions for the SQL and business side, data scientist interview questions for statistics and experiments, and machine learning interview questions for what happens after the data is clean.

A live data task is half code and half explanation, and the explanation is what candidates skip under time pressure. Natively, an AI interview assistant for Mac and Windows, can listen to a mock round on your computer and give you a transcript, so you can see whether you said your checks out loud or only typed them. During practice it can read a task or a traceback from a screenshot and suggest a fix or a cleaner vectorized version, and with Pro or the free trial it can draw on the résumé and job description you add. Your notes and transcript stay saved for review.

Questions people ask

What pandas questions are asked in data interviews?

Series versus DataFrame, loc versus iloc, boolean filtering, groupby with agg and transform, merge types and duplicate keys, pivot_table and melt, missing values, dtypes and memory, and why apply is slower than vectorized code.

What are common NumPy interview questions?

Why arrays beat lists for math, shapes and axes, the broadcasting rule, views versus copies, np.where for conditional logic, NaN handling and the difference between element-wise multiplication and matrix multiplication.

What is the difference between loc and iloc in pandas?

loc selects by label and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing.

How should I prepare for a live pandas coding round?

Practice timed tasks on real datasets: load, check types and nulls, filter, group, merge and report. Say your checks out loud, predict row counts before joins, and replace row-wise apply with vectorized operations.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP