Quick answer: Good Python for data science practice problems move in four steps: plain Python (counting, averages, cleaning text), NumPy (filtering, scaling, axis), pandas (filtering, missing values, groupby, merge, dates) and model metrics such as precision and recall. Try each of these 15 problems for 15 minutes on paper or in a notebook before you read the solution.
These Python for data science practice problems are small on purpose. Each uses a few rows, so you can work out the answer by hand and check your code against it.
There are 15 problems in four levels. You start with plain Python, move to NumPy and pandas, and finish by calculating model metrics yourself. If loops and functions are still new, begin with our Python basics practice problems.
How to use these Python for data science exercises
- Read the problem and write the expected answer on paper.
- Code for 15 minutes without looking at the solution.
- Compare your code with ours. A different method is fine if the answer is right.
- Change the data: add a missing value, a duplicate or an empty list. See what breaks.
- Write it again the next day from memory.
Pro tip: Step 4 is the most useful one. Real data is messy, and interviewers love to ask, "What if this value is missing?"
Level 1: Plain Python problems
1. Count how often each city appears
Given a list of cities, return a dictionary of counts.
def count_items(items):
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
return counts
print(count_items(["Hyd", "Vizag", "Hyd", "Guntur"]))
# {'Hyd': 2, 'Vizag': 1, 'Guntur': 1}
counts.get(item, 0) returns 0 the first time an item appears. This is the same idea behind value_counts() in pandas.
2. Find the average without a library
Return the mean of a list, or None if the list is empty.
def mean(values):
if not values:
return None
return sum(values) / len(values)
print(mean([72, 85, 90, 61])) # 77.0
print(mean([])) # None
Without the first check, an empty list causes a ZeroDivisionError.
3. Find the median
The median is the middle value after sorting. With an even count, it is the average of the two middle values.
def median(values):
data = sorted(values)
n = len(data)
mid = n // 2
if n % 2 == 1:
return data[mid]
return (data[mid - 1] + data[mid]) / 2
print(median([9, 2, 5])) # 5
print(median([7, 1, 5, 3])) # 4.0
sorted makes a new list, so the original order stays safe. Compare both averages on our mean, median and mode page.
4. Clean price text
Turn messy price strings into whole numbers.
def clean_price(text):
digits = "".join(ch for ch in text if ch.isdigit())
return int(digits) if digits else None
prices = ["Rs 1,200", " 850/-", "rs 2,499 ", "N/A"]
print([clean_price(p) for p in prices])
# [1200, 850, 2499, None]
This works for whole rupees only. A price like "99.50" would become 9950, so decimals need a different rule. Always state such limits.
5. Replace missing values with the average
Use the average of the known values to fill each None.
def fill_with_mean(values):
known = [v for v in values if v is not None]
if not known:
return values
average = sum(known) / len(known)
return [average if v is None else v for v in values]
print(fill_with_mean([10, None, 20, None, 30]))
# [10, 20.0, 20, 20.0, 30]
Notice is not None. Writing if v would also throw away real zeros.
Level 2: NumPy problems
6. Select marks above the class average
import numpy as np
marks = np.array([45, 78, 62, 90, 55])
above = marks[marks > marks.mean()]
print(marks.mean()) # 66.0
print(above.tolist()) # [78, 90]
marks > marks.mean() makes an array of true and false values. NumPy keeps only the true positions. No loop is needed.
7. Scale values between 0 and 1
Min-max scaling uses (x - min) / (max - min).
import numpy as np
def min_max(values):
x = np.array(values, dtype=float)
spread = x.max() - x.min()
if spread == 0:
return np.zeros_like(x)
return (x - x.min()) / spread
print(min_max([10, 20, 30, 50]).tolist()) # [0.0, 0.25, 0.5, 1.0]
print(min_max([7, 7]).tolist()) # [0.0, 0.0]
If every value is the same, the spread is 0 and normal division would fail. Read about normalisation and standardisation to see when each is used.
8. Total by shop and average by month
Rows are shops and columns are months.
import numpy as np
sales = np.array([[10, 20, 30], [5, 15, 25]])
print(sales.sum(axis=1).tolist()) # [60, 45]
print(sales.mean(axis=0).tolist()) # [7.5, 17.5, 27.5]
axis=1 gives one answer per row, which means per shop. axis=0 gives one answer per column, which means per month.
Level 3: pandas problems
9. Filter with two conditions
Find CSE students who scored more than 70.
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi", "Meena", "Kiran"],
"dept": ["CSE", "CSE", "ECE", "CSE"],
"marks": [88, 65, 91, 74],
})
good = df[(df["dept"] == "CSE") & (df["marks"] > 70)]
print(good["name"].tolist()) # ['Asha', 'Kiran']
Use & and not and. Put each condition in brackets.
10. Fill missing values using the group median
A missing temperature should be filled with the median of its own city.
import pandas as pd
df = pd.DataFrame({
"city": ["Hyd", "Hyd", "Hyd", "Vizag", "Vizag"],
"temp": [30, None, 34, 28, None],
})
city_median = df.groupby("city")["temp"].transform("median")
df["temp"] = df["temp"].fillna(city_median)
print(df["temp"].tolist()) # [30.0, 32.0, 34.0, 28.0, 28.0]
transform returns one value per original row, so it lines up with the table. That is why it fits better here than agg.
Common mistake: Filling both cities with one overall median. It gives a number, but the number ignores the fact that the two cities have different weather.
11. Find the department with the best average
import pandas as pd
df = pd.DataFrame({
"dept": ["CSE", "ECE", "CSE", "ECE", "EEE"],
"marks": [80, 70, 90, 78, 81],
})
avg = df.groupby("dept")["marks"].mean()
print(avg.to_dict()) # {'CSE': 85.0, 'ECE': 74.0, 'EEE': 81.0}
print(avg.idxmax()) # CSE
idxmax returns the label of the highest value. EEE has just one student, so also check the group size before drawing a conclusion.
12. Find customers with no orders
import pandas as pd
customers = pd.DataFrame({"id": [1, 2, 3], "name": ["Asha", "Ravi", "Meena"]})
orders = pd.DataFrame({"id": [1, 1, 3], "amount": [500, 200, 900]})
joined = customers.merge(orders, on="id", how="left")
missing = joined[joined["amount"].isna()]
print(missing["name"].tolist()) # ['Ravi']
A left merge keeps every customer. Customers without a match get NaN in amount. An inner merge would have removed Ravi completely.
13. Calculate monthly sales
import pandas as pd
df = pd.DataFrame({
"date": ["05-01-2027", "20-01-2027", "03-02-2027"],
"amount": [100, 250, 300],
})
df["date"] = pd.to_datetime(df["date"], format="%d-%m-%Y")
monthly = df.groupby(df["date"].dt.month)["amount"].sum()
print(monthly.to_dict()) # {1: 350, 2: 300}
The format says the day comes first. If your data covers more than one year, group by year and month together. Otherwise January 2026 and January 2027 get mixed.
14. Find the best-selling product in each city
import pandas as pd
df = pd.DataFrame({
"city": ["Hyd", "Hyd", "Vizag", "Vizag"],
"product": ["pen", "book", "pen", "bag"],
"qty": [40, 25, 15, 30],
})
best = df.sort_values("qty", ascending=False).drop_duplicates("city")
print(best[["city", "product"]].values.tolist())
# [['Hyd', 'pen'], ['Vizag', 'bag']]
Sort first, then keep the first row for each city. If two products tie, this keeps only one. Ask the interviewer whether ties matter.
Level 4: Model metrics problem
15. Calculate accuracy, precision and recall
Use 1 for spam and 0 for not spam. Do not use scikit-learn.
def metrics(actual, predicted):
pairs = list(zip(actual, predicted))
tp = sum(a == 1 and p == 1 for a, p in pairs)
fp = sum(a == 0 and p == 1 for a, p in pairs)
fn = sum(a == 1 and p == 0 for a, p in pairs)
correct = sum(a == p for a, p in pairs)
accuracy = correct / len(pairs)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
return round(accuracy, 2), precision, recall
print(metrics([1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1]))
# (0.67, 0.75, 0.75)
There are 3 true positives, 1 false positive and 1 false negative. So precision is 3/4 and recall is 3/4. Four of six answers are correct, which gives 0.67 accuracy.
Interview note: Be ready for the follow-up: "Which matters more for spam?" If good emails must not be lost, precision matters more. For a disease screening test, recall usually matters more.
Where to go after these Python for data science practice problems
| If you found this hard | Do this next |
|---|---|
| Level 1 | Redo it, then solve more Python basics problems |
| Level 2 | Read the NumPy introduction and write shapes on paper |
| Level 3 | Study pandas merge and repeat problems 10 to 14 |
| Level 4 | Revise machine learning basics |
| Nothing | Start one of the five project ideas |
Regular Python for data science coding practice works best when you mix it with theory. Use the interview questions to test your explanations, and the mistakes guide when an answer looks wrong. If you want Python for data science problems and solutions as part of a full plan with SQL and machine learning, the data science course guide sets out the order.
Frequently asked questions
Are these problems suitable for beginners?
Yes, if you know variables, loops, lists and functions. Level 1 uses plain Python only. If loops still feel hard, solve a set of Python basics problems first and come back after a week or two.
How many problems should I solve each day?
Two or three problems a day is enough if you write the code yourself and redo it the next day. Speed comes later. Understanding why each line is there matters more than finishing the list.
Do I need to install anything to practise?
You need Python with NumPy and pandas. You can install them with pip on your laptop or use a free cloud notebook in a browser. A laptop with 8 GB of RAM is comfortable for all of these problems.
Where can I find more data to practise on?
Use open data portals such as data.gov.in, public datasets on Kaggle or your own expense records. Start with a file of a few hundred rows so you can check answers by hand.
Will these problems help in interviews?
Yes. Data interviews often ask you to filter, group, merge and clean a small table, and to explain precision and recall. Practise saying your steps out loud as you code.
Want someone to check your solutions? Book a free demo class for the Data Science with AI course. Batches are capped at 27 students, so each learner gets personal attention.
