Academic Block

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 csv module.
  • 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 with Counter.
  • 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.

What this code does: It stores four sales records for a coffee shop chain as CSV text and reads them with 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__)

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.

What this code does: It reads five sales records, two of which are broken: one has an empty quantity and one has the word 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"])

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.

What this code does: It stores the daily revenue of one store for seven days. It prints the total, the mean, the median, the largest and smallest day, and the standard deviation, all rounded where needed.
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))

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 at 0.0, which is ideal for totals.
  • defaultdict(int) starts every new key at 0, 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.

What this code does: It stores six sales as pairs of a store and an amount. One loop adds the amounts to a total for each store and counts the sales. A second loop prints, for each store in alphabetical order, the total revenue and the average sale.
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")

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.

What this code does: It stores a list of ten drink orders and counts them with 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")

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.

What this code does: It stores the monthly revenue of four drinks in a dictionary and prints the total. It then sorts the drinks from the largest to the smallest revenue and prints the percentage share of each one. At the end, it adds up the two biggest drinks and prints their combined share.
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")

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.

What this code does: It stores five sales with dates written as text. For each sale, it works out the name of the weekday and adds the amount to that day in a dictionary. It prints the dictionary, finds the best weekday, and adds up the weekend sales.
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)

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 :+.1f always 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.

What this code does: It stores the sales of seven days of a week. It prints the average, lists the days that are above the average, and then goes through the days to find day-to-day changes of at least 30 percent in either direction. Each big change is printed with its sign.
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]}")
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.

What this code does: It stores five sales records and asks which store to report on. It cleans the answer, collects the sales of that store, and prints the number of sales, the total, and the best-selling item by revenue. If the store has no sales, it prints a message instead.
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})")

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.

What this code does: It stores the sales of seven days and asks for a daily goal in dollars. The conversion to a float is protected by 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}")

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() or float(), 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 statistics for mean, median, and standard deviation, and compare the mean with the median.
  • Group with defaultdict, and rank with Counter.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.

Ready for the next step?Turn your numbers into charts and graphs that tell the story at a glance.
Next: Data Visualization Project →