pandas Practice: Student Grades, Sales and an Employee Cleanup
Three small pandas jobs end to end: a student grades workflow exported to CSV, a sales challenge with groupby and a supplier merge, and an employee cleanup where one missing value hides as text. Each answer is checked against its list.
What you will learn
- Run a full pandas workflow: create, explore, filter, transform and export
- Write a Role, Context, Task, Format prompt for a data job and treat the answer as one possible result
- Check AI-written pandas output against each requirement, with totals and row counts
- Clean a messy table: hidden missing values, text salaries, median fill and duplicates
Before you start
- pandas loc, iloc and filtering
- pandas data cleaning
- pandas groupby and merge
You've learned DataFrames, reading and writing files, selecting, cleaning, groupby and merge. Now you'll use them together, the way you would on a small job: a student grades mini project, a sales challenge and an employee cleanup.
Think about going shopping with a list. You come home with a bag and a receipt. You don't just trust the bag: you hold the list next to the receipt and tick each item, and if the milk isn't there you catch it right away. It's the same with code from an AI tool. Your requirements are the list, and the output is the receipt.
Mini project: student grades
The workflow is create, explore, filter, transform and export. The prompt uses the four parts from prompting fundamentals:
- Role: a Python tutor who writes simple pandas.
- Context: six students, each with a name and a score.
- Task: build the DataFrame, explore it, keep scores of 60 or more, add a letter grade, save it to
grades.csv. - Format: short code that prints each step, and no index in the file.
What comes back is one possible result. Your tool may write it differently, and that's fine as long as it meets the list. Here it's split into small files, one step each.
Create and explore
import pandas as pd
df = pd.DataFrame({
"name": ["Alice", "Bob", "Carol",
"David", "Eve", "Frank"],
"score": [85, 42, 91, 60, 73, 55],
})
print(df.info())
print(df.describe())
<class 'pandas.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 6 non-null str
1 score 6 non-null int64
dtypes: int64(1), str(1)
memory usage: 228.0 bytes
None
score
count 6.000000
mean 67.666667
std 18.715413
min 42.000000
25% 56.250000
50% 66.500000
75% 82.000000
max 91.000000
That None? info() prints by itself and returns nothing, so print shows None. Six rows, nothing missing, scores from 42 to 91.
Filter the passes
passed = df[df["score"] >= 60]
print(passed)
print(len(passed), "of", len(df), "passed")
name score
0 Alice 85
2 Carol 91
3 David 60
4 Eve 73
4 of 6 passed
Check it against the list: David has exactly 60 and he's in, so >= is the right test.
Add the grade, and export
from pathlib import Path
df["grade"] = df["score"].apply(
lambda x: "A" if x >= 90
else "B" if x >= 80
else "C" if x >= 70
else "D" if x >= 60
else "F"
)
df.to_csv("grades.csv", index=False)
print(Path("grades.csv").exists())
print(pd.read_csv("grades.csv"))
True
name score grade
0 Alice 85 B
1 Bob 42 F
2 Carol 91 A
3 David 60 D
4 Eve 73 C
5 Frank 55 F
apply runs the small lambda once per score. Carol's 91 passes the first check and gets an A; the rest are never looked at. Bob and Frank pass nothing and fall through to F. index=False keeps the row numbers out of the file (otherwise you'd read back an Unnamed: 0 column, as in pandas data IO). The file lands in the folder you ran the script from. The whole list is ticked.
One more question each with groupby and merge
per_grade = df.groupby("grade")["score"].agg(
["count", "mean"]
)
print(per_grade)
count mean
grade
A 1 91.0
B 1 85.0
C 1 73.0
D 1 60.0
F 2 48.5
advisors = pd.DataFrame({
"grade": ["A", "B", "C", "D", "F"],
"advisor": ["Ms. Rao", "Mr. Lee", "Ms. Rao",
"Mr. Lee", "Ms. Cruz"],
})
report = df.merge(advisors, on="grade")
print(report)
name score grade advisor
0 Alice 85 B Mr. Lee
1 Bob 42 F Ms. Cruz
2 Carol 91 A Ms. Rao
3 David 60 D Mr. Lee
4 Eve 73 C Ms. Rao
5 Frank 55 F Ms. Cruz
Bob and Frank both have an F, so the same advisor row goes to both of them.
Challenge one: sales data
Six products with a price and a quantity. Four tasks: add a total column, find the most expensive product, keep rows where quantity is more than 5, and print the total revenue. Think in DataFrames, not loops. Pause here if you want to write your own prompt first (Role: a data analyst who uses pandas; Context: this table; Task: those four jobs; Format: short code that prints each answer). One possible result:
import pandas as pd
sales = pd.DataFrame({
"product": ["Laptop", "Mouse", "Keyboard",
"Monitor", "Webcam", "Headset"],
"price": [999, 25, 75, 450, 60, 85],
"quantity": [3, 15, 8, 2, 12, 6],
})
sales["total"] = sales["price"] * sales["quantity"]
print(sales)
top = sales.loc[sales["price"].idxmax()]
print(top)
busy = sales[sales["quantity"] > 5]
print(busy)
print(sales["total"].sum())
product price quantity total
0 Laptop 999 3 2997
1 Mouse 25 15 375
2 Keyboard 75 8 600
3 Monitor 450 2 900
4 Webcam 60 12 720
5 Headset 85 6 510
product Laptop
price 999
quantity 3
total 2997
Name: 0, dtype: object
product price quantity total
1 Mouse 25 15 375
2 Keyboard 75 8 600
4 Webcam 60 12 720
5 Headset 85 6 510
6102
idxmax gives the row label of the highest price, and loc pulls out that whole row.
One more thing: "most expensive" here means price, not total. Both happen to give the Laptop, but they're different questions, so read your requirement carefully.
Group by kind, merge the suppliers
sales["kind"] = ["Computer", "Accessory", "Accessory",
"Computer", "Accessory", "Accessory"]
by_kind = sales.groupby("kind")["total"].sum()
print(by_kind)
kind
Accessory 2205
Computer 3897
Name: total, dtype: int64
suppliers = pd.DataFrame({
"product": ["Laptop", "Mouse", "Keyboard",
"Monitor", "Webcam", "Headset"],
"supplier": ["Nova", "Pixel", "Pixel",
"Nova", "Orbit", "Orbit"],
})
full = sales.merge(suppliers, on="product")
print(full.groupby("supplier")["total"].sum())
supplier
Nova 3897
Orbit 1230
Pixel 975
Name: total, dtype: int64
Here's a check you can always do: the group totals must add back to the revenue. 3897 + 2205 = 6102, and 3897 + 1230 + 975 = 6102. So the merge didn't lose or repeat a row.
Challenge two: employee cleanup
This table is messy. Bob's dept is None. Carol's salary is NaN and Eve's is the text "N/A". The other salaries are in quotes, so they're text. And Alice appears twice. Tasks: count what's missing, fill the missing dept with "Unknown", convert salary to numbers, fill missing salaries with the median, remove duplicates, print the clean table. In your prompt's context, describe the table and what's wrong with it, because the tool can't see your data.
Why convert salary at all?
import pandas as pd
salary = pd.Series(["50000", "60000", "45000"])
print(salary.iloc[0] + 5000)
Traceback (most recent call last):
File "S06L05_Practice\cleanup_text_salary.py", line 4, in <module>
print(salary.iloc[0] + 5000)
~~~~~~~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "int") to str
Numbers stored as text can't do maths. One possible result for the cleanup:
import numpy as np
import pandas as pd
messy = pd.DataFrame({
"name": ["Alice", "Bob", "Carol",
"Alice", "David", "Eve"],
"dept": ["Sales", None, "IT",
"Sales", "HR", "IT"],
"salary": ["50000", "60000", np.nan,
"50000", "45000", "N/A"],
})
print(messy.isna().sum())
messy["dept"] = messy["dept"].fillna("Unknown")
messy["salary"] = pd.to_numeric(
messy["salary"], errors="coerce"
)
messy["salary"] = messy["salary"].fillna(
messy["salary"].median()
)
clean = messy.drop_duplicates()
print(clean)
name 0
dept 1
salary 1
dtype: int64
name dept salary
0 Alice Sales 50000.0
1 Bob Unknown 60000.0
2 Carol IT 50000.0
4 David HR 45000.0
5 Eve IT 50000.0
Look at the first count. Salary has two bad values, but it reports one: "N/A" is only text at that point, so it isn't counted. to_numeric(errors="coerce") turns it into NaN, and only then is it seen as missing. The four good salaries have a median of 50,000, which fills both Carol and Eve. drop_duplicates removes Alice's copy, and the index shows the gap (0, 1, 2, 4, 5) because pandas keeps the original labels. The tools are the ones from data cleaning and wrangling.
Read the numbers carefully
by_dept = clean.groupby("dept")["salary"].mean()
print(by_dept)
dept
HR 45000.0
IT 50000.0
Sales 50000.0
Unknown 60000.0
Name: salary, dtype: float64
IT shows 50,000. But Carol and Eve are the only two people in IT, and both were filled with the median. So that number is the fill, not anyone's recorded pay. The code ran fine, and the number still needs a careful read. That part is your job, not the tool's.
floors = pd.DataFrame({
"dept": ["Sales", "IT", "HR", "Unknown"],
"floor": [1, 2, 3, 4],
})
staff = clean.merge(floors, on="dept")
print(staff)
name dept salary floor
0 Alice Sales 50000.0 1
1 Bob Unknown 60000.0 4
2 Carol IT 50000.0 2
3 David HR 45000.0 3
4 Eve IT 50000.0 2
Bob gets floor 4 because the floors table includes "Unknown". If it didn't, an inner merge would drop Bob without a word. Five rows in, five rows out. When you merge, check the row count every time.
Recap
| Habit | How |
|---|---|
| Ask clearly | Role, Context, Task, Format; describe your table in the context |
| Treat code as one possible result | Read it step by step |
| Tick the list | Each requirement against a printed line |
| Catch lost or doubled rows | Group totals add back to the grand total; rows in equals rows out |
| Read filled values honestly | A group made only of filled values tells you about the fill |
Try it yourself: pick one challenge, write your own prompt without copying this one, and check the output against your list.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
