For data analyst roles, Python means pandas far more than it means algorithms. Interviewers want to see you load a messy dataset, filter it, group it, join it to another table and hand back a clean answer. This page covers the pandas and Python questions that recur in analyst interviews, with idiomatic code and the reasoning that separates someone who has read a tutorial from someone who works in DataFrames daily.
How to answer Python questions
Prefer the built-in, vectorized pandas method and say why. When an interviewer sees you reach for groupby or a boolean mask instead of a for loop over rows, they read it as real experience. Narrate what each line returns — a Series, a DataFrame, a scalar — because confusing those is the usual source of pandas bugs.
Q1. What is the difference between a Series and a DataFrame?
A Series is a one-dimensional labeled array — a single column with an index. A DataFrame is a two-dimensional labeled table, essentially a dictionary of Series sharing one index. Selecting a single column from a DataFrame returns a Series.
Knowing this shapes everything downstream: df['price'] gives a Series you can do arithmetic on, while df[['price']] (double brackets) gives a one-column DataFrame. Interviewers use the distinction to check whether you understand what your expressions actually produce.
import pandas as pd
df = pd.DataFrame({"product": ["A", "B", "C"], "price": [100, 250, 90]})
print(type(df["price"])) # <class 'pandas.core.series.Series'>
print(type(df[["price"]])) # <class 'pandas.core.frame.DataFrame'>
Interview note: Trap: "what does df.values return?" A NumPy array, dropping the labels — useful, but you lose the index and column names.
Q2. Explain loc versus iloc.
loc selects by label (row index and column names); iloc selects by integer position. A subtle difference: loc slices are inclusive of the end label, while iloc slices follow normal Python half-open semantics and exclude the end.
df.loc[0:2, "price"] # rows with labels 0,1,2 — end INCLUDED
df.iloc[0:2, 1] # rows in positions 0,1 — end EXCLUDED
The inclusive-versus-exclusive gap is a favorite gotcha. Being able to state it precisely, and to use boolean masks with loc (df.loc[df.price > 100]), marks you as someone who filters data for real.
Interview note: Follow-up: "why prefer loc for conditional assignment?"
df.loc[mask, 'col'] = valueavoids the chained-indexing SettingWithCopyWarning thatdf[mask]['col'] = valuetriggers.
Q3. How do you handle missing values in pandas?
Detect them with isna(); drop them with dropna(); fill them with fillna(). The choice depends on the column: drop rows when missingness is rare and random, and impute (mean, median, mode, or forward-fill for time series) when dropping would lose too much data.
df["price"] = df["price"].fillna(df["price"].median()) # robust to outliers
df = df.dropna(subset=["customer_id"]) # can't analyze without it
The interviewer is really asking whether you think before you fill. Filling a categorical column with a mean is nonsense; forward-filling a random survey is wrong. Explaining why you chose median over mean (skew, outliers) is the scoring moment.
Interview note: Trap: "does fillna modify in place?" By default it returns a new object; you must reassign or pass inplace. Assuming it mutates silently leads to lost changes.
Q4. What does groupby do, and how do you aggregate?
groupby splits the DataFrame into groups by one or more keys, applies an aggregation to each group, and combines the results — the split-apply-combine pattern. It mirrors SQL's GROUP BY.
summary = (
df.groupby("region")
.agg(total_sales=("sales", "sum"),
avg_order=("sales", "mean"),
orders=("sales", "count"))
.reset_index()
)
The named-aggregation syntax above is the modern, readable form and signals current pandas knowledge. Interviewers often follow with "now filter to regions with more than 1000 total sales", testing whether you know to aggregate first and filter the result — the pandas analogue of HAVING.
Interview note: Follow-up: "why reset_index()?" groupby puts the keys in the index; reset_index turns them back into ordinary columns for joining or exporting.
Q5. What is the difference between merge, join and concat?
merge combines DataFrames on key columns like a SQL join (inner, left, right, outer). join is a convenience method that merges on the index by default. concat stacks DataFrames vertically or horizontally without matching keys.
merged = pd.merge(orders, customers, on="customer_id", how="left")
stacked = pd.concat([jan_df, feb_df], ignore_index=True) # append rows
Analysts most often want a left merge to enrich a fact table with lookup attributes. Knowing that how="left" keeps all order rows even when a customer record is missing — and produces NaN for the missing side — is the practical point.
Interview note: Trap: "merge on a column with duplicates?" It produces a many-to-many cross product, silently exploding row counts. Check key uniqueness before merging.
Q6. Why avoid iterrows, and what do you use instead?
iterrows loops row by row in Python, which is slow and loses dtype information. Prefer vectorized operations, which apply to whole columns at C speed. Use map or apply only when no vectorized equivalent exists.
# slow: for idx, row in df.iterrows(): ...
df["margin"] = df["price"] - df["cost"] # vectorized, fast
df["tier"] = df["price"].apply(lambda p: "high" if p > 200 else "low")
The first line does elementwise subtraction across the whole column at once. Interviewers ask this because reflexively writing loops is the clearest sign of someone new to pandas.
Interview note: Follow-up: "is apply vectorized?" Not really — apply still calls a Python function per element or row. It is cleaner than iterrows but slower than true vectorized arithmetic.
Q7. How do you create a new column conditionally?
For a binary condition use numpy.where; for multiple conditions use numpy.select or pandas cut for binning. These stay vectorized, unlike a Python loop.
import numpy as np
df["status"] = np.where(df["days_late"] > 0, "late", "on_time")
df["band"] = pd.cut(df["price"], bins=[0, 100, 300, np.inf],
labels=["low", "mid", "high"])
Binning continuous values into labeled bands with cut is an everyday analyst task (age groups, price tiers), and reaching for it rather than nested conditionals reads as fluency.
Interview note: Trap: "cut vs qcut?" cut uses fixed value edges; qcut uses quantiles so each bin holds roughly equal counts. Choose based on whether you want equal ranges or equal group sizes.
Q8. How do you reshape data with pivot and melt?
pivot_table turns long data into wide (rows into columns) with an aggregation; melt does the reverse, turning wide columns into long key-value rows. Analysts pivot for reporting layouts and melt to tidy data for plotting.
wide = df.pivot_table(index="region", columns="month",
values="sales", aggfunc="sum")
long = wide.reset_index().melt(id_vars="region",
var_name="month", value_name="sales")
Understanding "tidy" data — one observation per row, one variable per column — is what these operations serve. Many plotting and modeling tools expect long format, so melt is often the last cleaning step.
Interview note: Follow-up: "pivot vs pivot_table?" pivot fails on duplicate index/column pairs; pivot_table aggregates them, which is why it is the safer default.
What interviewers really test
Python rounds for analysts reward idiomatic pandas and careful data handling far more than clever algorithms. The recurring signal is whether you vectorize, whether you think before imputing, and whether you know what each expression returns. Pair this page with the data cleaning questions, where these pandas methods do the real work, and the SQL for analysts set, since interviewers often ask you to translate between the two. A structured Data Analytics path and a focused mock interview will build the muscle memory that makes DataFrames feel effortless.
Frequently Asked Questions
How much Python does a data analyst need for interviews?
Which pandas topics are most common in interviews?
What is the difference between loc and iloc in pandas?
Should analysts use loops or vectorization in pandas?
Is Python or SQL more important for a data analyst?
Want to Build Your Career in Data Analytics with AI?
Join CodeBegun and train with working industry engineers — Explore the Data Analytics program

