Pandas Interview Questions and Answers
Last updated 2026-11-19
Pandas shows up in almost every data analyst, data scientist and data engineer interview that includes Python. The questions are rarely about obscure functions. They test whether you can reshape, join and aggregate data correctly, avoid silent bugs such as duplicated join keys, and write vectorised code instead of loops.
Each answer below has code that runs as written on a small example, with the result stated. After this page, practise on the wider set in Python interview questions, and pair it with SQL using how to crack the SQL interview, because many pandas tasks are SQL tasks in disguise.
| Typical rounds | Python data task, take-home analysis, live pandas coding |
|---|---|
| Core skills | groupby, merge, datetime, reshaping, performance |
| Questions here | 15 worked questions |
Patterns worth knowing cold
- groupby with agg, transform and apply, and when each returns what.
- merge types, key uniqueness checks and the row-multiplication trap.
- Top-N per group, ranking and de-duplication with a tie rule.
- Datetime handling: parsing, dt accessor, resample and rolling windows.
- Performance: vectorisation, category dtype, chunked reading.
How to approach a pandas coding question
Print the shape and dtypes first, then state what one output row represents. Build the answer in small steps, checking the shape after each. Avoid iterrows unless you can explain why vectorised code is not possible, and finish by checking that keys you expect to be unique really are.
Pandas Interview Questions and Answers: questions with worked answers
1 What is the difference between loc, iloc, at and iat?
easyloc selects by label and includes the end of a slice, iloc selects by integer position and excludes the end. at and iat are faster versions for a single scalar by label or position. A boolean mask works with loc, which is also the safe way to assign. With a default RangeIndex, df.loc[0:2] returns three rows but df.iloc[0:2] returns two.
pythonimport pandas as pd df = pd.DataFrame({'a': [10, 20, 30, 40]}, index=[0, 1, 2, 3]) print(len(df.loc[0:2]), len(df.iloc[0:2])) # 3 2 df.loc[df['a'] > 25, 'a'] = 0 # safe conditional assignment2 Explain the merge types. What happens to the row count with duplicate keys?
mediumWith left keys [1, 2, 3] and right keys [2, 3, 4], inner gives 2 rows, left gives 3, right gives 3 and outer gives 4. If a key appears 2 times on the left and 3 times on the right, that key produces 2 x 3 = 6 rows, which silently inflates totals. Protect against it with validate="one_to_one" or "one_to_many", and use indicator=True to see which side each row came from.
pythonleft = pd.DataFrame({'k': [1, 2, 3], 'x': ['a', 'b', 'c']}) right = pd.DataFrame({'k': [2, 3, 4], 'y': ['p', 'q', 'r']}) print(len(left.merge(right, on='k'))) # 2 print(len(left.merge(right, on='k', how='outer'))) # 4 left.merge(right, on='k', how='left', validate='one_to_one', indicator=True)3 Difference between agg, transform and apply in groupby?
mediumagg reduces each group to one row. transform returns a result with the same length and index as the input, so it can be assigned back as a column. apply is the flexible one that can return anything but is slower. For sales of 10, 20, 30, 50 in regions A, A, B, B, a sum transform gives 30, 30, 80, 80, so each row's share of its region is 0.333, 0.667, 0.375, 0.625.
pythondf = pd.DataFrame({'region': list('AABB'), 'sales': [10, 20, 30, 50]}) df['region_total'] = df.groupby('region')['sales'].transform('sum') df['share'] = (df['sales'] / df['region_total']).round(3) summary = df.groupby('region').agg(total=('sales', 'sum'), avg=('sales', 'mean'))4 Get the top 2 rows by sales within each region.
mediumSort by the value descending, then take head(2) per group. This is simple and fast. If ties must be handled in a specific way, use groupby rank with method="first" or "dense" and filter. Reset the index at the end if you do not need the group labels. The equivalent in SQL is a ROW_NUMBER filter.
pythontop2 = (df.sort_values('sales', ascending=False) .groupby('region').head(2) .sort_values(['region', 'sales'], ascending=[True, False])) # ranking alternative df['rk'] = df.groupby('region')['sales'].rank(method='first', ascending=False) top2_alt = df[df['rk'] <= 2]5 Fill missing ages with the median age of each city.
mediumUse groupby transform so the median is computed per city and returned aligned to every row, then fillna with it. A global median would blur real differences between groups. If a whole city has no ages, its median is NaN, so follow with a global fallback.
pythondf['age'] = df['age'].fillna(df.groupby('city')['age'].transform('median')) df['age'] = df['age'].fillna(df['age'].median()) # fallback6 Why is apply with a Python function slow, and what is the alternative?
easyapply with axis=1 calls the Python function once per row, with all the interpreter overhead, whereas vectorised operations run in compiled loops over whole columns. Replace row logic with arithmetic, np.where, np.select or string accessors. On a million rows a vectorised expression typically runs tens to hundreds of times faster. Keep apply for logic that truly cannot be expressed in column operations.
pythonimport numpy as np # slow df['band'] = df.apply(lambda r: 'high' if r['sales'] > 25 else 'low', axis=1) # fast df['band'] = np.where(df['sales'] > 25, 'high', 'low')7 What is the SettingWithCopyWarning and how do you avoid it?
mediumIt warns that you may be assigning to a copy of a slice rather than the original frame, as in df[df.a > 0]["b"] = 1, which does chained indexing and may not change df. Use a single indexing operation, df.loc[df.a > 0, "b"] = 1, or call .copy() when you deliberately want an independent frame. With copy-on-write (the default in pandas 3), chained assignment never updates the original, so the habit of using loc becomes essential.
8 Reshape: wide to long with melt, and long to wide with pivot.
mediummelt turns columns into rows, which is useful for plotting and tidy data. pivot does the reverse and requires unique index and column pairs, or it raises an error; pivot_table aggregates duplicates instead.
pythonwide = pd.DataFrame({'id': [1, 2], 'jan': [5, 7], 'feb': [6, 8]}) long = wide.melt(id_vars='id', var_name='month', value_name='sales') # 4 rows back = long.pivot(index='id', columns='month', values='sales')9 Parse dates and compute monthly totals and a 3-month rolling mean.
mediumConvert with to_datetime, set it as the index, resample to month end and sum, then roll. The rolling window needs one row per month, which resample guarantees. The first two values are NaN because min_periods defaults to the window size. Use errors="coerce" to turn bad strings into NaT and then inspect them.
pythondf['date'] = pd.to_datetime(df['date'], errors='coerce') monthly = df.set_index('date')['sales'].resample('ME').sum() # 'M' in older pandas roll = monthly.rolling(3).mean()10 How would you reduce the memory use of a large DataFrame?
mediumCheck df.memory_usage(deep=True). Convert low-cardinality string columns to category, downcast numerics (int64 to int32 or int16, float64 to float32) when the range allows, read only needed columns with usecols, and give dtype hints at read time. For files too large for memory, use chunksize and aggregate each chunk, or switch to Parquet, Dask or Polars. A string column with 5 unique values over 10 million rows shrinks dramatically as category.
pythondf['city'] = df['city'].astype('category') df['qty'] = pd.to_numeric(df['qty'], downcast='integer') total = 0 for chunk in pd.read_csv('big.csv', usecols=['amount'], chunksize=500_000): total += chunk['amount'].sum()11 Remove duplicates, keeping the latest record per customer.
easySort by the timestamp and call drop_duplicates on the key with keep="last". Without the sort, drop_duplicates keeps whichever row appears first in current order, which is rarely what you want. For an audit, use duplicated(keep=False) to see every row that has a duplicate.
pythonlatest = (df.sort_values('updated_at') .drop_duplicates(subset='customer_id', keep='last'))12 Split a comma-separated column into rows.
mediumUse str.split to create lists and then explode, which repeats the other columns for every list element. A row with "a,b,c" becomes three rows. Strip whitespace after splitting. Rows with an empty list become NaN rows after explode.
pythondf = pd.DataFrame({'id': [1, 2], 'tags': ['a, b, c', 'x']}) out = (df.assign(tags=df['tags'].str.split(r'\s*,\s*')) .explode('tags')) # 4 rows13 Difference between cut and qcut?
easycut makes bins with chosen edges, so equal-width by default, and counts per bin can differ a lot. qcut makes bins by quantiles, so each bin holds roughly the same number of rows. For ages you might use cut with edges [0, 18, 60, 100] to get meaningful bands, and qcut with q=4 to get quartiles of income.
pythonages = pd.Series([5, 17, 25, 40, 70]) bands = pd.cut(ages, bins=[0, 18, 60, 100], labels=['child', 'adult', 'senior']) quartiles = pd.qcut(pd.Series(range(1, 9)), 4, labels=False) # 0,0,1,1,2,2,3,314 Compute year-over-year or day-over-day change within each group.
mediumSort by time, then use groupby with shift or pct_change so values from one group never leak into another. Without the groupby, the first row of each group would be compared with the last row of the previous group. The first row per group is NaN by design.
pythondf = df.sort_values(['product', 'date']) df['prev'] = df.groupby('product')['sales'].shift(1) df['pct'] = df.groupby('product')['sales'].pct_change() * 100
Frequently asked questions
Is pandas enough, or do I need Polars or PySpark?
Pandas is the interview default. Know the idea of PySpark for large data, which the PySpark page covers, but most screening tasks use pandas.
Do interviewers allow documentation?
Rarely in live rounds and often in take-homes. Know the signatures of the common calls, such as merge, groupby, pivot_table and to_datetime.
How do I practise pandas for interviews?
Take SQL practice problems and solve each with pandas as well. Check results against both approaches.
What are the most common pandas mistakes in interviews?
Chained assignment, forgetting that merge on duplicate keys multiplies rows, using apply where vectorised code exists and forgetting to sort before shift or drop_duplicates.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Performance Testing and JMeter Interview Questions
- Power BI Interview Questions and Answers
- Probability for Data Science Interview Questions and Answers
- Product Analyst Interview Questions and Answers
- PySpark Interview Questions and Answers
- React Hooks Interview Questions and Answers
- React Interview Questions and Answers (React 19)
- React Native Interview Questions and Answers
- Redux Interview Questions and Answers (Redux Toolkit)
- SDET Interview Questions and Answers
- Selenium Interview Questions and Answers
- Site Reliability Engineer (SRE) Interview Questions and Answers