Python Interview Questions for Data Analysts: 15 Business Tasks With Answers and Code

Gulab Chand Tejwani
PMP · PL-300 · Microsoft Certified Trainer
· 10 min read

Python interview questions for data analysts are mostly business questions you answer with code: which products grew month over month, who the top customers are in each city, which values are outliers, how many customers came back. Interviewers check three things: whether you can turn a vague question into the right calculation, whether your pandas is clean, and whether you sanity-check the result before presenting it. The fifteen tasks below cover the patterns that come up most.
I'm Gulab Chand Tejwani from TechNet Consultancy. I teach data analysis to working professionals, and I've helped several companies run analyst interviews. The candidates who stand out don't write the cleverest code. They ask "what counts as an active customer here?" before writing anything, and they notice when a number looks wrong.
What do data analyst Python interviews test?
Usually a mix of short concept questions and one practical task on a small dataset, often a CSV of orders or users. Some companies give a take-home notebook. The concept side overlaps with general pandas interview questions; this post focuses on the practical side.

All examples use this sales data:
import pandas as pd
import numpy as np
sales = pd.DataFrame({
"order_id": range(1, 13),
"customer": ["A", "B", "C", "A", "D", "B", "E", "A", "C", "F", "B", "G"],
"city": ["Anand", "Surat", "Anand", "Anand", "Surat", "Surat",
"Vadodara", "Anand", "Anand", "Vadodara", "Surat", "Anand"],
"product": ["Pen", "Book", "Pen", "Bag", "Book", "Pen",
"Bag", "Book", "Bag", "Pen", "Bag", "Pen"],
"amount": [120, 450, 80, 900, 300, 150, 1100, 400, 850, 90, 950, 15000],
"order_date": pd.to_datetime([
"2026-08-03", "2026-08-10", "2026-08-21", "2026-09-02",
"2026-09-08", "2026-09-15", "2026-09-28", "2026-10-01",
"2026-10-05", "2026-10-12", "2026-10-19", "2026-10-30",
]),
})
sales["month"] = sales["order_date"].dt.to_period("M")
Trend and growth tasks
1. What is monthly revenue, and how much did it grow month over month?
monthly = sales.groupby("month")["amount"].sum()
growth = monthly.pct_change().mul(100).round(1)
print(pd.DataFrame({"revenue": monthly, "mom_growth_%": growth}))
August is 650, September 2,450 and October 17,290. The jump to October looks dramatic, and that's your cue for task 7: one order is suspiciously large.
2. What is the running total of revenue?
monthly.cumsum()
3. What is each month's revenue by product, as a table?
sales.pivot_table(index="month", columns="product", values="amount", aggfunc="sum", fill_value=0)
Ranking and share tasks
4. Who are the top 2 customers by revenue in each city?
This "top N per group" pattern comes up constantly.
by_cust = sales.groupby(["city", "customer"], as_index=False)["amount"].sum()
top2 = (
by_cust.sort_values(["city", "amount"], ascending=[True, False])
.groupby("city")
.head(2)
)
print(top2)
Mention ties: if two customers have the same amount, decide whether both should appear (use rank(method="dense")) or just one.
5. What share of total revenue does each product contribute?
share = sales.groupby("product")["amount"].sum()
print((share / share.sum() * 100).round(1).sort_values(ascending=False))
6. Which customers make up 80% of revenue?
cust = sales.groupby("customer")["amount"].sum().sort_values(ascending=False)
cum_share = cust.cumsum() / cust.sum()
# keep each customer whose running share *before* them is still under 80%
print(cust[cum_share.shift(fill_value=0) < 0.8].index.tolist()) # ['G', 'B']
The shift matters: filtering on cum_share <= 0.8 would stop at G (74%) and never reach 80%. Including the customer who carries the total past the line, B here (81%), answers the question as asked. In this data, one customer (G) is 74% of revenue on a single order, which makes the list very short. That's worth saying out loud, because it's a business insight and a data quality question at the same time.
| Business question | pandas pattern | Watch out for |
|---|---|---|
| Growth over time | groupby(period).sum() then pct_change() | Missing months, partial months |
| Top N per group | sort_values then groupby().head(n) | Ties |
| Share of total | groupby().sum() / total | Dividing by a filtered total by mistake |
| Outliers | IQR or z-score on the column | Removing real but rare values |
| Retention | First purchase month per customer, then compare | Defining 'returned' |
Data quality tasks
7. How would you find outliers in order amounts?
The IQR rule is easy to explain: anything above Q3 + 1.5 × IQR or below Q1 − 1.5 × IQR is flagged.
q1, q3 = sales["amount"].quantile([0.25, 0.75])
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = sales[(sales["amount"] < lower) | (sales["amount"] > upper)]
print(outliers[["order_id", "customer", "amount"]])
Order 12 (15,000) is flagged. Then say what you'd do: check with the business whether it's a real bulk order or a data entry error before removing anything. Deleting an outlier that's actually your biggest customer is a classic analyst mistake.
8. How do you check a dataset before analysing it?
sales.info()
sales.isna().sum()
sales.duplicated(subset=["order_id"]).sum()
sales.describe()
sales["order_date"].agg(["min", "max"])
Five lines, and they catch most problems: wrong types, missing values, duplicate IDs, impossible values (negative amounts) and date ranges that don't match what you were told.
9. Dates arrive as text in mixed formats. What do you do?
raw = pd.Series(["2026-10-01", "01/10/2026", "not a date"])
iso = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
indian = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce")
parsed = iso.fillna(indian)
print(parsed.isna().sum()) # 1 value couldn't be parsed
Parse each known format explicitly, then combine. errors="coerce" turns anything that doesn't match into a missing value you can count and inspect. The shortcut pd.to_datetime(raw, format="mixed", dayfirst=True) looks tempting, but when I tested it on pandas 3 it read "2026-10-01" as 10 January. Mention that trap and you'll stand out, because wrong dates that don't raise an error are worse than dates that fail.
10. Customer names have inconsistent spacing and case. How do you clean them?
names = pd.Series([" asha patel", "ASHA PATEL ", "Asha Patel"])
clean = names.str.strip().str.replace(r"\s+", " ", regex=True).str.title()
print(clean.nunique(), clean.iloc[0]) # 1 Asha Patel
Customer behaviour tasks
11. How many customers bought again after their first month?
first = sales.groupby("customer")["month"].min().rename("first_month")
s = sales.join(first, on="customer")
returned = s[s["month"] > s["first_month"]]["customer"].nunique()
total = sales["customer"].nunique()
print(f"{returned} of {total} customers returned") # 3 of 7
Clarify what "returned" means first: any later purchase, or a purchase within 30 days?
12. What is the average order value by city, and is the difference meaningful?
sales.groupby("city")["amount"].agg(["count", "mean", "median"]).round(0)
Showing the median next to the mean is the point here. Anand's mean is pulled up by one huge order; the median tells a calmer story. With only a few orders per city, say that you wouldn't draw strong conclusions.
13. How many days pass between a customer's orders?
gaps = (
sales.sort_values(["customer", "order_date"])
.groupby("customer")["order_date"]
.diff()
.dt.days
)
print(gaps.dropna().describe())
Tools and judgement questions
14. When would you use Python instead of SQL or Excel?
A balanced answer: SQL to pull and aggregate data where it lives, Excel for quick checks and sharing with non-technical people, Python when the cleaning or logic gets complicated, when the task repeats (automate it), or when you need statistics and charts beyond what the others do easily. Most analyst jobs use all three. SQL queries for data analysis covers the SQL side.
15. How would you present the result of task 1 to a manager?
Not as a DataFrame. One sentence, one chart, one caveat: "Revenue grew from 650 in August to 17,290 in October, but most of October comes from one 15,000 order that we should confirm before reporting." That sentence is what the whole exercise was for.

Practice questions
You need the top 3 products by revenue within each region. Which approach is correct?
- Adf.nlargest(3, 'revenue')
- BAggregate revenue by region and product, sort by region then revenue descending, then groupby('region').head(3)
- Cdf.groupby('region').max().head(3)
- Ddf.sort_values('revenue').tail(3)
Show answer and explanation
Correct answer: B
A and D return the top 3 overall, not per region. C returns the max of every column per region, which mixes values from different rows. B aggregates first, then takes three rows per region.
Your monthly revenue chart shows a huge spike in one month. What should you do first?
- ARemove the month from the chart
- BReport it as strong growth
- CReplace the month's value with the average
- DLook at the largest orders in that month and check whether they're real
Show answer and explanation
Correct answer: D
A spike is a question, not a conclusion. Look at the rows driving it, confirm with the business, then decide. Removing or smoothing data without checking can hide real events.
Order values are heavily right-skewed: most orders are small, a few are very large. Which summary best describes a typical order?
- AMedian
- BMean
- CMaximum
- DSum
Show answer and explanation
Correct answer: A
The median isn't pulled up by a few large values, so it describes a typical order better when data is skewed. Report the mean too if totals matter, but explain the difference.
How should you prepare for a data analyst Python interview?
Take one realistic dataset (orders, website sessions, HR data) and work through the fifteen tasks above on it. Then do it again on a second dataset without looking at your code. Practise saying your answer in one sentence for a manager. That last step is the one most candidates skip and most interviewers notice.
Python interview practice has a data analyst track with exercises like these, run in your browser with pandas and NumPy, with hints, test checks and worked answers. The bank has 200+ questions for a one-time ₹199. Since analyst rounds almost always include SQL too, the SQL interview practice store lets you start free with the ShopX company set. For the Excel side, see Excel skills for data analysts.
FAQ
What Python skills do data analysts need for interviews?
pandas for loading, cleaning, grouping and joining data, basic NumPy, date handling, simple statistics (mean, median, percentiles) and the ability to explain a result in business terms. Charts with matplotlib or seaborn help too.
Do data analyst interviews ask coding questions?
Usually practical ones: answer a business question on a small dataset with pandas or SQL. Algorithm puzzles are less common for analyst roles than for developer roles.
Is Python required for data analyst jobs in India?
Not for every role. Many analyst jobs need Excel, SQL and Power BI first. Python is increasingly listed, especially at product companies and for roles with automation or larger datasets.
How do I find outliers in Python?
A common method is the IQR rule: compute Q1 and Q3, then flag values above Q3 + 1.5 × IQR or below Q1 − 1.5 × IQR. Always check flagged values with the business before removing them.
How long does it take to learn Python for data analysis?
With regular practice, most people can handle typical analyst interview tasks in pandas after six to ten weeks, faster if they already know SQL or Excel well.