Python Data Analysis ProjectGet Certified
What Is a Data Analysis Project?
A data analysis project takes raw records, such as the sales slips of a coffee shop chain, and turns them into answers: which store sells the most, which item is the favorite, which days are the busiest, and where the business is growing or falling behind. Every project of this kind follows the same path. You load the data, clean out the bad records, calculate summary numbers, compare groups, look for patterns over time, and report what you found. In this lesson you will walk through that path step by step with a small coffee shop dataset, and each example is one stage of a real analysis that you can reuse with your own data.
- Load: read CSV text with the
csvmodule. - Clean: convert text to numbers and skip the broken rows.
- Summarize: total, mean, median, minimum, maximum, and standard deviation with
statistics. - Group and rank: totals per store with
defaultdict, and best sellers withCounter. - Explore patterns: sales by weekday, shares of revenue, and big changes from day to day.
- Report: let the user choose a store or a goal and print a short summary.
Step 1: Load the Data
Every analysis starts with getting the data into the program. Most real datasets come as CSV files, which are plain text files with one record per line and the values separated by commas, and Python’s csv module reads them without any extra library. The class csv.DictReader uses the first line as the column names and gives you every row as a dictionary, so you can write row["store"] instead of remembering a column position. In this lesson the CSV data is stored in a text variable and opened with io.StringIO, which makes the text behave like a file, and with a real file you would simply write open("sales.csv") instead.
Try It: Reading Sales Records
Click Test My Code. Add another line of data inside the triple quotes and check that the row count grows.
csv.DictReader. It prints the number of rows, the column names, the store and quantity of the first row, and the type of the quantity value, which shows that it is still text.import csv
import io
csv_text = """date,store,item,quantity,price
2026-11-02,Seattle,Latte,12,4.50
2026-11-02,Austin,Mocha,8,5.00
2026-11-03,Seattle,Espresso,15,3.00
2026-11-03,Boston,Latte,10,4.50
"""
rows = list(csv.DictReader(io.StringIO(csv_text)))
print(len(rows))
print(list(rows[0].keys()))
print(rows[0]["store"], rows[0]["quantity"])
print(type(rows[0]["quantity"]).__name__)csv module knows how to split lines of comma-separated values.io module provides StringIO, which makes text behave like an open file.DictReader turns each line into a dictionary, and list() collects all of them.4.['date', 'store', 'item', 'quantity', 'price'].Seattle 12.str.Step 2: Clean the Data
Real data is messy: a cashier forgets to type a quantity, a typo turns a number into a word, or a price is left blank. If such rows reach your calculations, the program either crashes or produces wrong totals, so cleaning is a required step and often the longest one of a project. The usual approach is to convert each value to the right type inside a try block and to skip every row that raises a ValueError. Always count the rows that you skip and report the number, because silently throwing away data can hide a serious problem in the source.
Try It: Skipping Broken Rows
Click Test My Code. Fix the broken quantity in the Boston row and see the kept count rise.
ten instead of a number. A loop converts the quantity and the price, keeps the good rows in a list, and counts the skipped ones. The program prints the counts and the revenue of the second kept row.import csv
import io
csv_text = """store,item,quantity,price
Seattle,Latte,12,4.50
Austin,Mocha,,5.00
Boston,Latte,ten,4.50
Denver,Espresso,15,3.00
Austin,Latte,9,4.50
"""
clean = []
skipped = 0
for row in csv.DictReader(io.StringIO(csv_text)):
try:
row["quantity"] = int(row["quantity"])
row["price"] = float(row["price"])
clean.append(row)
except ValueError:
skipped += 1
print(f"Kept {len(clean)} rows, skipped {skipped}")
print(clean[1]["store"], clean[1]["quantity"] * clean[1]["price"])csv module reads the records.io module makes the text behave like a file.int() will fail on it.ten, which cannot be converted.ValueError.ValueError of a broken row.Kept 3 rows, skipped 2.Denver 45.0.Step 3: Summary Statistics
Once the data is clean, the first questions are usually simple: how much in total, what is typical, and how spread out are the numbers? The statistics module of the standard library answers them with mean(), median(), and stdev(), while sum(), max(), and min() are built into Python. The mean is the average, the median is the middle value after sorting, and the standard deviation tells how far the values typically are from the mean. If the mean and the median are far apart, a few unusually large or small values are pulling the average, and that is worth a closer look.
Try It: A Week of Daily Revenue
Click Test My Code. Change 702.50 to 2000 and see how much more the mean moves than the median.
import statistics
daily_revenue = [420.50, 515.00, 389.25, 610.75, 455.00, 702.50, 498.00]
print(round(sum(daily_revenue), 2))
print(round(statistics.mean(daily_revenue), 2))
print(statistics.median(daily_revenue))
print(max(daily_revenue), min(daily_revenue))
print(round(statistics.stdev(daily_revenue), 2))statistics module provides mean(), median(), and stdev().3591.0.513.0.498.0.702.5 389.25.stdev() measures how far the days typically are from the mean, and it is rounded to two decimals. The output is 110.25.Step 4: Group and Compare
Totals for the whole company hide the differences between its parts, so the next step is to group the records by a category such as the store, the item, or the month. In plain Python, a dictionary does this job well, and collections.defaultdict makes it shorter because a missing key starts with a default value, such as 0.0 for a running total. You loop over the records once, add each amount to the total of its group, and count the records in each group, so that you can calculate the average as well. Sorting the group names gives a report in a predictable order.
defaultdict(float)starts every new key at0.0, which is ideal for totals.defaultdict(int)starts every new key at0, which is ideal for counts.- One loop can update several dictionaries at the same time.
sorted(totals)gives the keys in alphabetical order.
Try It: Revenue per Store
Click Test My Code. Add a sale for a new store, such as Denver, and see it appear in the report.
from collections import defaultdict
sales = [
("Seattle", 54.00), ("Austin", 40.00), ("Seattle", 45.00),
("Boston", 45.00), ("Austin", 40.50), ("Boston", 52.50),
]
totals = defaultdict(float)
counts = defaultdict(int)
for store, amount in sales:
totals[store] += amount
counts[store] += 1
for store in sorted(totals):
average = totals[store] / counts[store]
print(f"{store}: ${totals[store]:,.2f} total, ${average:,.2f} average")defaultdict is a dictionary that creates a starting value for a missing key.Austin: $80.50 total, $40.25 average, Boston: $97.50 total, $48.75 average, and Seattle: $99.00 total, $49.50 average.Step 5: Rank the Results
After comparing groups, the next natural question is which one is first. For counting, the Counter class from collections is the perfect tool: you give it a list, and it returns a dictionary-like object that maps each item to the number of times that it appears. Its method most_common(n) returns the n biggest entries as pairs, already sorted from the largest count to the smallest. A Counter also returns 0 for an item that never appeared, instead of raising a KeyError, which makes it very convenient for reports.
Try It: The Best-Selling Drink
Click Test My Code. Add five more "Tea" orders to the list and see how the ranking changes.
Counter. It prints the two most common drinks, names the best seller with its number of orders, shows the counts of one drink that was sold and one that was not, and prints how many different drinks appear.from collections import Counter
orders = ["Latte", "Mocha", "Latte", "Espresso", "Latte", "Mocha", "Tea", "Espresso", "Latte", "Mocha"]
counts = Counter(orders)
print(counts.most_common(2))
best, number = counts.most_common(1)[0]
print(f"Best seller: {best} ({number} orders)")
print(counts["Tea"], counts["Cocoa"])
print(len(counts), "different items")Counter counts how often each item appears in a list.most_common(2) returns the two biggest entries as pairs. The output is [('Latte', 4), ('Mocha', 3)].most_common(1) returns a list with one pair, and [0] takes that pair, which is unpacked into two variables.Best seller: Latte (4 orders).1 0.4 different items.Step 6: Calculate Shares and Percentages
Absolute numbers are useful, but a manager often wants to know what share of the money each product brings in. A share is the part divided by the total and multiplied by 100, and it makes groups of very different sizes easy to compare. Sorting the items by revenue, from the largest to the smallest, turns the shares into a ranking, and adding up the shares of the first few items shows how concentrated the business is. If a small number of products make up most of the revenue, those products deserve the most attention.
Try It: Revenue Share by Drink
Click Test My Code. Change the revenue of "Tea" to 1400 and see how the shares shift.
revenue = {"Latte": 1800.00, "Mocha": 1200.00, "Espresso": 600.00, "Tea": 400.00}
total = sum(revenue.values())
print(f"Total: ${total:,.2f}")
for item, amount in sorted(revenue.items(), key=lambda pair: pair[1], reverse=True):
share = amount / total * 100
print(f"{item:<10}{share:>6.1f}%")
top_two = sum(sorted(revenue.values(), reverse=True)[:2]) / total * 100
print(f"Top two items: {top_two:.0f}% of revenue")values() gives all the revenues, and sum() adds them up to 4000.Total: $4,000.00.[:2] keeps the first two, and their sum is turned into a percentage.Top two items: 75% of revenue.Step 7: Analyze Patterns Over Time
Sales almost always depend on time: weekends are busier than weekdays, the holiday season is bigger than the summer, and morning hours differ from the afternoon. To study such patterns, you need to turn a date written as text into something that Python understands, and the datetime module does this with date.fromisoformat(). The method strftime("%A") then gives the name of the weekday, so that you can group the sales by day of the week with the same dictionary technique as before. This kind of analysis answers practical questions, such as when to schedule more staff.
Try It: Sales by Weekday
Click Test My Code. Add a sale on "2026-11-10" and see which weekday grows.
from datetime import date
sales = [
("2026-11-02", 420), ("2026-11-03", 515), ("2026-11-07", 702),
("2026-11-08", 650), ("2026-11-09", 398),
]
by_day = {}
for text, amount in sales:
day = date.fromisoformat(text).strftime("%A")
by_day[day] = by_day.get(day, 0) + amount
print(by_day)
best = max(by_day, key=by_day.get)
print("Best day:", best)
weekend = by_day.get("Saturday", 0) + by_day.get("Sunday", 0)
print("Weekend total:", weekend)date class from the datetime module represents a calendar date.fromisoformat() turns the text into a date, and strftime("%A") gives the full name of the weekday, such as Monday.get(day, 0) returns the total so far, or 0 for a new weekday, and the amount is added.{'Monday': 818, 'Tuesday': 515, 'Saturday': 702, 'Sunday': 650}.max() with key=by_day.get returns the weekday with the largest total.Best day: Monday.get() with 0 avoids an error if a day is missing.Weekend total: 1352.Step 8: Find Highlights and Big Changes
The last analysis step is to look for what stands out: the days that beat the average and the moments when sales jumped or dropped sharply. Comparing each value with the mean shows the above-average days, and the percent change between two neighboring days, calculated as the difference divided by the earlier value and multiplied by 100, shows how fast sales moved. A threshold, such as 30 percent, keeps the report short by printing only the large changes. These highlights are the findings that you would put at the top of a report for a manager.
- A list comprehension with
zip()pairs each day name with its value and filters the days above the average. - Percent change is
(new - old) / old * 100, and the base is always the earlier value. abs()checks the size of a change, whether it is up or down.- The format
:+.1falways shows the sign of a number.
Try It: Above-Average Days and Big Swings
Click Test My Code. Lower the limit from 30 to 20 and see which extra changes are reported.
weekly = [420, 515, 389, 610, 455, 702, 498]
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
average = sum(weekly) / len(weekly)
print(f"Average: ${average:,.2f}")
above = [day for day, value in zip(days, weekly) if value > average]
print("Above average:", above)
for i in range(1, len(weekly)):
change = (weekly[i] - weekly[i - 1]) / weekly[i - 1] * 100
if abs(change) >= 30:
print(f"{days[i]}: {change:+.1f}% vs {days[i - 1]}")Average: $512.71.zip() pairs each day name with its value, and the comprehension keeps the names of the days that are above the average.Above average: ['Tue', 'Thu', 'Sat'].abs() ignores the sign, so a rise and a drop of the same size are treated alike. The limit is 30 percent.:+.1f shows the sign. The output is Thu: +56.8% vs Wed and Sat: +54.3% vs Fri. Sunday fell by about 29 percent, which is just under the limit.Tip: Before you trust a result, check it in a second way: compare a total with a sum that you calculate by hand, look at the smallest and the largest values, and test your code on a tiny dataset whose answers you know. Round numbers only when you print them, and keep the full precision in your calculations. Finally, write down your assumptions, such as which rows you removed, so that others can repeat the analysis.
Interactive Reports with User Input
A report becomes much more useful when the reader can choose what to see, for example the store to look at or the sales goal to compare against. In a program, that means reading a value with input(), cleaning it so that small differences do not matter, and checking whether the data really contains it. The method strip() removes stray spaces, and title() turns seattle into Seattle, which makes matching more forgiving. Remember that input() always returns text, so numbers must be converted, and a conversion that can fail belongs inside a try block.
Try It: A Store Report
The Program Input box is already filled with seattle. Click Run Code straight away, then try Austin and Portland.
records = [
("Seattle", "Latte", 54.00),
("Austin", "Mocha", 40.00),
("Seattle", "Espresso", 45.00),
("Austin", "Latte", 40.50),
("Seattle", "Latte", 49.50),
]
store = input("Which store? ").strip().title()
matches = [(item, amount) for name, item, amount in records if name == store]
if not matches:
print(f"No sales found for {store}")
else:
total = sum(amount for item, amount in matches)
by_item = {}
for item, amount in matches:
by_item[item] = by_item.get(item, 0) + amount
best = max(by_item, key=by_item.get)
print(f"{store}: {len(matches)} sales, ${total:,.2f}")
print(f"Best item: {best} (${by_item[best]:,.2f})")seattle, is cleaned with strip() and title(), which gives Seattle.not matches is true when the store has no sales.Portland, the output is No sales found for Portland.Seattle: 3 sales, $148.50.Best item: Latte ($103.50).Try It: A Daily Sales Goal
The Program Input box is filled with 500. Click Run Code, then try 600 and a text such as abc.
try and except. If the number is valid, the program counts the days that reached the goal, lists them, and adds up how far the other days fell short.daily = {"Mon": 420, "Tue": 515, "Wed": 389, "Thu": 610, "Fri": 455, "Sat": 702, "Sun": 498}
try:
goal = float(input("Daily sales goal in dollars: "))
except ValueError:
print("Please enter a number")
else:
hits = [day for day, amount in daily.items() if amount >= goal]
print(f"{len(hits)} of {len(daily)} days reached ${goal:,.0f}")
print(hits)
shortfall = sum(goal - amount for amount in daily.values() if amount < goal)
print(f"Total shortfall: ${shortfall:,.2f}")500, is converted from text to the float 500.0.ValueError that float() raises for text such as abc.Please enter a number.3 of 7 days reached $500.['Tue', 'Thu', 'Sat'].sum() adds them: 80 for Monday, 111 for Wednesday, 45 for Friday, and 2 for Sunday.Total shortfall: $238.00.Common Mistakes in Data Analysis
Data analysis mistakes are dangerous because they rarely stop the program: the code runs happily and prints a confident but wrong number. Most of the errors come from a handful of habits, such as treating text as numbers, skipping the cleaning step, or trusting a single average. The list below covers the problems that appear most often, and it is worth reading before every new project and again when a result looks too good, or too strange, to be true.
- Not looking at the raw data first: print a few rows and check the column names before you calculate anything.
- Forgetting that CSV values are text: convert them with
int()orfloat(), or"12" + "8"becomes"128". - Silently dropping bad rows: count and report the rows that you skip, so that you notice a problem in the source.
- Relying only on the mean: a few huge values can distort it. Compare it with the median and look at the minimum and maximum.
- Dividing by zero: a group with no records has no average. Check the count first.
- Using the wrong base for a percent change: always divide by the earlier value, not the later one.
- Rounding too early: keep full precision in the calculations and round only for display.
- Not testing on a tiny dataset: try your code on a few rows whose answers you can check by hand.
Key Takeaways
A data analysis project is a sequence of small, understandable steps, and the tools for each step are already in Python: csv for loading, try and except for cleaning, statistics for summaries, defaultdict and Counter for grouping and ranking, and datetime for dates. The same steps apply when you use a larger library such as pandas, so what you learned here carries over directly. The points below summarize the lesson, and they prepare you for the next one, in which you will turn numbers like these into charts. Remember them whenever you open a new dataset.
- Follow the path: load, clean, summarize, group, rank, explore patterns, and report.
- Everything read from a CSV file is text, so convert it, and count the rows that cannot be converted.
- Use
statisticsfor mean, median, and standard deviation, and compare the mean with the median. - Group with
defaultdict, and rank withCounter.most_common(). - Shares and percent changes make groups of different sizes comparable. Divide by the total, or by the earlier value.
- Turn date text into dates with
date.fromisoformat()to analyze weekdays and other time patterns. - Check your results a second way, round only when printing, and write down your assumptions.
Frequently Asked Questions
These are the questions that students ask most often when they do their first data analysis project in Python. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try the steps on a small dataset of your own, such as your monthly spending or the scores of a sports team, because analyzing data that you care about is the fastest way to learn.
What are the steps of a data analysis project?
A typical project loads the data, cleans it by converting types and removing bad records, calculates summary statistics, groups and compares categories, looks for patterns over time, and reports the findings. Each step builds on the one before it, and it is good practice to check the results after every step.
How do I read a CSV file in Python without pandas?
Use the csv module that comes with Python. Open the file and pass it to csv.DictReader, which treats the first line as column names and returns each row as a dictionary, for example rows = list(csv.DictReader(open(“sales.csv”))). All values arrive as text, so convert numbers with int() or float().
Why is data cleaning important?
Real data contains missing values, typos, and wrong types. If they reach your calculations, the program can crash or, worse, give wrong totals without any warning. Cleaning converts values to the right types and removes or fixes broken records, and reporting how many records were removed keeps the analysis honest.
What is the difference between mean and median?
The mean is the sum of the values divided by their number, and the median is the middle value after sorting. A few very large or very small values can pull the mean away from the typical value, while the median stays steady. Comparing the two tells you whether unusual values are present.
How do I group data in Python?
Loop over the records and add each value to a dictionary entry for its category. A collections.defaultdict makes this short, because a missing key starts at a default such as 0.0. You can keep one dictionary for totals and another for counts, and then calculate the average for each group.
How do I find the most common item in a list?
Pass the list to collections.Counter and call most_common(). For example, Counter(orders).most_common(1) returns the item with the highest count together with that count. A Counter also returns 0 for an item that is not in the list, so it never raises a KeyError.
Should I use pandas or the standard library for data analysis?
The standard library is enough for small datasets and is a good way to learn the steps, because every operation is visible. Pandas is better for large tables, because it can filter, group, and combine data with much shorter code and runs faster. The ideas of loading, cleaning, grouping, and reporting are the same in both.
How can I check that my analysis results are correct?
Test your code on a tiny dataset whose answers you can calculate by hand, compare totals with an independent sum, and look at the smallest and the largest values for anything strange. Also check how many rows were skipped during cleaning. If a result looks too good or too odd, search for a mistake before you report it.