Analyze Sales Data with Python
Load, explore, and visualize sales data using pandas and matplotlib.
Introduction
30 Second Summary
Every business decision starts with data. Whether it's a coffee shop tracking which drinks sell best or a tech company monitoring revenue trends, the ability to turn raw numbers into clear insights is one of the most in-demand skills in the job market.
In this project, you will load a sales dataset, calculate business metrics, and create professional charts using Python. You'll do all of this inside Google Colab, a free browser-based tool that requires zero setup on your computer.
What You'll Build
A complete data analysis notebook that explores store sales data, calculates key insights like top-selling categories and revenue trends, and produces two polished visualizations.
By the end of this project, you'll have:
- A working Google Colab notebook that loads and explores a sales dataset using pandas.
- Summary statistics showing totals, averages, and revenue breakdowns by product category.
- Two professional matplotlib charts: a bar chart comparing revenue by category and a line chart showing daily sales trends.
- Secret Mission: Add a pie chart showing revenue distribution and export your notebook as a PDF report.
Are there any prerequisites?
You just need a free Google account to access Google Colab. No programming experience or software installation is required.
Set Up Google Colab
To analyze sales data with Python, you need somewhere to write and run your code.
Google Colab is a free, browser-based notebook tool from Google. It comes with Python and all the data science libraries you need pre-installed, so you can start coding immediately.
In this step, get ready to:
- Sign into Google Colab.
- Create and rename your analysis notebook.
Open Google Colab
Google Colab runs entirely in your browser. There is nothing to download or install.
- Open a new browser tab.
- Navigate to colab.research.google.com.
- Sign in with your Google account if prompted.
What is Google Colab?
Google Colab is a free online notebook environment. It lets you write Python code in "cells" and run each cell individually to see the output immediately below it.
Libraries like pandas and matplotlib come pre-installed, so you can focus on learning data analysis instead of wrestling with setup.
Create a new notebook
The Colab welcome screen shows recently opened notebooks. You need a fresh notebook for this project.
- Click New notebook in the bottom left of the welcome popup.
A new notebook opens with one empty code cell. This is where you will write Python code.
Rename your notebook
The default name is something generic like "Untitled0.ipynb". A descriptive name helps you find this notebook later.
- Click on the notebook title at the top left of the page (it says Untitled0.ipynb or similar).
- Replace the text with Sales Data Analysis and press Enter.
The title at the top of your notebook now reads Sales Data Analysis.ipynb.
Don't see the welcome popup?
If the welcome popup did not appear, click File in the top menu bar, then click New notebook.
If you see an error about signing in, make sure you are logged into a Google account in your browser.
Help me troubleshoot Google Colab setup issues.
Your notebook is ready. Next up, you will create a sales dataset and load it into Python using pandas.
Create Your Dataset and Load It with Pandas
Your notebook is open and ready to go. Now it's time to fill it with data.
Every data analysis project starts with a dataset. In this step, you'll create a sample sales dataset directly inside your notebook using a Python dictionary, then convert it into a pandas DataFrame so you can start exploring it.
In this step, get ready to:
- Create a sales dataset as a pandas DataFrame.
- Explore the dataset's structure and contents.
- Add a markdown cell documenting what the data contains.
Import libraries and create the dataset
Before you can work with data, you need to import the Python libraries that give you the tools to do so. Your notebook already has one empty code cell waiting for you.
- Click into the empty code cell in your notebook and paste the following code:
# Cell 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
- Run the cell by clicking the play button on the left side of the cell, or press Shift+Enter.
What does this code do?
These two lines import the libraries you'll use throughout this project.
- `import pandas as pd` loads pandas (the data analysis library) and gives it the shortcut name pd.
- `import matplotlib.pyplot as plt` loads matplotlib's plotting module and gives it the shortcut name plt.
The cell runs without any visible output. That's normal for import statements.
Now you'll create the dataset. You need a new code cell below your imports.
- Click the + Code button in the toolbar at the top of the notebook to add a new code cell.
- Paste the following code into the new cell:
# Cell 2: Create the sales dataset
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03',
'2024-01-03', '2024-01-04', '2024-01-04', '2024-01-05', '2024-01-05',
'2024-01-06', '2024-01-06', '2024-01-07', '2024-01-07', '2024-01-08',
'2024-01-08', '2024-01-09', '2024-01-09', '2024-01-10', '2024-01-10'],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Laptop',
'Headphones', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Electronics',
'Accessories', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'],
'Quantity': [2, 5, 3, 1, 1, 4, 6, 2, 2, 3,
1, 4, 5, 1, 2, 3, 7, 3, 2, 5],
'Price': [999.99, 29.99, 79.99, 349.99, 999.99,
59.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99]
}
df = pd.DataFrame(data)
print("Dataset created successfully!")
print(f"Shape: {df.shape[0]} rows, {df.shape[1]} columns")
What does this code do?
This cell builds your entire sales dataset from scratch.
- The data dictionary holds five columns: Date, Product, Category, Quantity, and Price. Each key maps to a list of 20 values (one per transaction).
- `pd.DataFrame(data)` converts the dictionary into a pandas DataFrame, which is a table-like structure that lets you filter, sort, and analyze the data.
- The print statements confirm the dataset loaded correctly and show its dimensions.
- Run the cell by pressing Shift+Enter.
You should see the output: Dataset created successfully! followed by Shape: 20 rows, 5 columns.
Seeing a NameError?
If you see NameError: name 'pd' is not defined, it means Cell 1 (the imports) hasn't been run yet. Go back to Cell 1 and run it first.
In Colab, cells must be run in order. Each cell depends on the code from the cells above it. Help me fix this NameError in my Colab notebook.
Explore the dataset
Now that your data is loaded, you can inspect it to understand its structure. Pandas gives you several built-in methods to peek at your data without scrolling through all 20 rows.
- Click the + Code button to add another new code cell.
- Paste the following code into the new cell:
# Cell 3: Explore the data
print("First 5 rows:")
print(df.head())
print("\nDataset info:")
print(df.info())
print("\nColumn types:")
print(df.dtypes)
What do these methods show you?
- `df.head()` displays the first 5 rows of your DataFrame so you can quickly see what the data looks like.
- `df.info()` shows the number of entries, column names, data types, and whether any values are missing.
- `df.dtypes` lists the data type of each column (e.g., object for text, int64 for whole numbers, float64 for decimals).
- Run the cell by pressing Shift+Enter.
You should see a table showing the first 5 rows of your data, followed by a summary of column types and row counts.
Output looks jumbled or cut off?
Colab sometimes truncates wide tables. If columns are missing, try running df.head() in its own cell without the other print statements. This lets Colab render it as a formatted table.
Help me read my DataFrame output in Colab.
Add a markdown cell to describe your dataset
Good notebooks include written explanations alongside code. A markdown cell at the top of your notebook tells anyone reading it what the dataset contains.
- Click on your first code cell (Cell 1) to select it.
- Click the + Text button in the toolbar. This adds a text cell above the selected cell.
- Type the following into the text cell:
# Sales Data Analysis
This notebook analyzes a sample store sales dataset containing 20 transactions.
**Columns:**
- Date: Transaction date (Jan 1-10, 2024)
- Product: Item sold (Laptop, Mouse, Keyboard, Monitor, Headphones)
- Category: Product category (Electronics, Accessories)
- Quantity: Number of items purchased
- Price: Unit price in USD
What is a markdown cell?
Markdown cells display formatted text instead of running code. They support headings (using #), bold text (using **), and bullet lists (using -). Data scientists use them to document their analysis steps and findings.
- Click outside the text cell or press Shift+Enter to render the markdown.
You should see a formatted heading, description, and bullet list appear above your code cells.
✔️ Awesome, I've got everything!
Great. Double check you've saved your notebook. Colab auto-saves, but you can also press Ctrl+S (Windows) or Cmd+S (macOS) to be safe.
ⓧ I'd like to double check the full code
Here is everything your notebook should contain so far. Compare each cell against yours.
# Cell 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Cell 2: Create the sales dataset
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03',
'2024-01-03', '2024-01-04', '2024-01-04', '2024-01-05', '2024-01-05',
'2024-01-06', '2024-01-06', '2024-01-07', '2024-01-07', '2024-01-08',
'2024-01-08', '2024-01-09', '2024-01-09', '2024-01-10', '2024-01-10'],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Laptop',
'Headphones', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Electronics',
'Accessories', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'],
'Quantity': [2, 5, 3, 1, 1, 4, 6, 2, 2, 3,
1, 4, 5, 1, 2, 3, 7, 3, 2, 5],
'Price': [999.99, 29.99, 79.99, 349.99, 999.99,
59.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99]
}
df = pd.DataFrame(data)
print("Dataset created successfully!")
print(f"Shape: {df.shape[0]} rows, {df.shape[1]} columns")
# Cell 3: Explore the data
print("First 5 rows:")
print(df.head())
print("\nDataset info:")
print(df.info())
print("\nColumn types:")
print(df.dtypes)
Your notebook now has real data to work with. Next up, you'll dig into this dataset and pull out meaningful business insights using summary statistics and groupby aggregations.
Explore and Summarize the Data
You now have a DataFrame loaded and you know its basic shape. The next question is: what story does this data tell?
In this step, you will calculate summary statistics, derive new columns, and group data to extract meaningful business insights from your sales records.
In this step, get ready to:
- Generate summary statistics for all numeric columns.
- Calculate total revenue, average order value, and transaction count.
- Group data by product category to find revenue breakdowns.
Generate summary statistics with describe()
Raw data is hard to interpret row by row. Summary statistics give you a bird's-eye view of your numbers: the averages, the extremes, and the spread.
Before you can summarize revenue, you need to create a Revenue column. Revenue is simply the quantity sold multiplied by the unit price.
- Create a new code cell below your existing cells by clicking the + Code button at the top of the notebook.
- Add the Revenue column and generate summary statistics by pasting this code:
# Cell 4: Add a Revenue column and generate summary statistics
df['Revenue'] = df['Quantity'] * df['Price']
print("Summary statistics:")
print(df.describe())
What does this code do?
The first line creates a new column called Revenue by multiplying each row's Quantity by its Price. This is called a derived column because it's calculated from existing data.
The df.describe() method generates count, mean, standard deviation, min, max, and quartile values for every numeric column in one call.
- Run the cell by pressing Shift+Enter.
- You should see a table with rows like count, mean, std, min, and max for columns including your new Revenue column.
Not seeing the Revenue column in the output?
Make sure you ran Cell 2 first. Cell 4 depends on the df variable that Cell 2 creates.
If you see a NameError, click on Cell 2 and press Shift+Enter to re-run it, then run Cell 4 again.
help me debug my describe() output in Google Colab
Calculate key business metrics
Summary statistics show the spread of your data, but business stakeholders want specific numbers. Total revenue, average order value, and transaction count are the metrics that answer the question: how is the business doing?
- Create a new code cell by clicking + Code.
- Calculate and display business metrics by pasting this code:
# Cell 5: Calculate key business metrics
total_revenue = df['Revenue'].sum()
avg_order_value = df['Revenue'].mean()
total_transactions = len(df)
print(f"\nTotal Revenue: ${total_revenue:,.2f}")
print(f"Average Order Value: ${avg_order_value:,.2f}")
print(f"Total Transactions: {total_transactions}")
What does this code do?
- .sum() adds up every value in the Revenue column to get the total.
- .mean() calculates the average revenue per transaction.
- len(df) counts the number of rows, which equals the number of transactions in this dataset.
- The f"..." syntax is a Python f-string that lets you embed variables directly inside text. The :,.2f part formats numbers with commas and two decimal places.
- Run the cell by pressing Shift+Enter.
- You should see three printed lines showing your Total Revenue, Average Order Value, and Total Transactions as formatted dollar amounts and a count.
Seeing a KeyError for Revenue?
This means Cell 4 has not been run yet. The Revenue column only exists after Cell 4 executes. Run Cell 4 first, then re-run Cell 5.
help me fix a KeyError in my pandas notebook
Group revenue by product category
Totals are useful, but they hide which parts of the business are performing best. Grouping data by a category column lets you compare segments side by side.
- Create a new code cell by clicking + Code.
- Group revenue by category by pasting this code:
# Cell 6: Group by category
category_revenue = df.groupby('Category')['Revenue'].sum()
print("\nRevenue by Category:")
print(category_revenue)
What is groupby?
The groupby() method splits your DataFrame into groups based on a column's unique values. Here, it creates one group for Accessories and one for Electronics.
After grouping, .sum() adds up the Revenue within each group. Think of it like a pivot table in a spreadsheet.
- Run the cell by pressing Shift+Enter.
- You should see two rows printed: one for Accessories and one for Electronics, each with a total revenue dollar amount.
Output looks wrong or shows NaN?
Double-check that the column name in your groupby matches exactly: 'Category' with a capital C. Column names in pandas are case-sensitive.
If you see NaN values, make sure Cell 4 ran successfully. That cell creates the Revenue column that Cell 6 depends on.
help me fix my groupby output
✔️ Awesome, I've got everything!
Great. Double-check you have Cells 4, 5, and 6 all showing output before moving on.
ⓧ I'd like to double check the full code
Here is the complete notebook code up to this point. Compare your cells against this:
# Cell 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Cell 2: Create the sales dataset
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03',
'2024-01-03', '2024-01-04', '2024-01-04', '2024-01-05', '2024-01-05',
'2024-01-06', '2024-01-06', '2024-01-07', '2024-01-07', '2024-01-08',
'2024-01-08', '2024-01-09', '2024-01-09', '2024-01-10', '2024-01-10'],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Laptop',
'Headphones', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Electronics',
'Accessories', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'],
'Quantity': [2, 5, 3, 1, 1, 4, 6, 2, 2, 3,
1, 4, 5, 1, 2, 3, 7, 3, 2, 5],
'Price': [999.99, 29.99, 79.99, 349.99, 999.99,
59.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99]
}
df = pd.DataFrame(data)
print("Dataset created successfully!")
print(f"Shape: {df.shape[0]} rows, {df.shape[1]} columns")
# Cell 3: Explore the data
print("First 5 rows:")
print(df.head())
print("\nDataset info:")
print(df.info())
print("\nColumn types:")
print(df.dtypes)
# Cell 4: Add a Revenue column and generate summary statistics
df['Revenue'] = df['Quantity'] * df['Price']
print("Summary statistics:")
print(df.describe())
# Cell 5: Calculate key business metrics
total_revenue = df['Revenue'].sum()
avg_order_value = df['Revenue'].mean()
total_transactions = len(df)
print(f"\nTotal Revenue: ${total_revenue:,.2f}")
print(f"Average Order Value: ${avg_order_value:,.2f}")
print(f"Total Transactions: {total_transactions}")
# Cell 6: Group by category
category_revenue = df.groupby('Category')['Revenue'].sum()
print("\nRevenue by Category:")
print(category_revenue)
You now have hard numbers on revenue, order values, and category performance. Next up, you will turn these numbers into visual charts that communicate your findings at a glance.
Visualize Your Findings
You now have concrete numbers about your sales data. You know the total revenue, average order value, and how revenue breaks down by category.
Numbers alone can be hard to interpret at a glance. Charts make patterns instantly visible. In this step, you will create two visualizations using matplotlib to turn your analysis into something presentation-ready.
In this step, get ready to:
- Create a bar chart comparing total revenue by product category.
- Create a line chart showing daily revenue trends over time.
- Add titles, axis labels, and colors to make your charts presentation-ready.
Create a bar chart of revenue by category
A bar chart is ideal for comparing values across categories. You already have category_revenue from the previous step, so you can plot it directly.
- Create a new code cell in your notebook and paste the following code:
# Cell 7: Bar chart - Revenue by Category
plt.figure(figsize=(8, 5))
plt.bar(category_revenue.index, category_revenue.values, color=['#2196F3', '#4CAF50'])
plt.title('Total Revenue by Product Category', fontsize=14)
plt.xlabel('Category', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.tight_layout()
plt.show()
What does this code do?
This cell creates a bar chart using the category_revenue data you calculated in the previous step.
- plt.figure(figsize=(8, 5)) creates a new figure that is 8 inches wide and 5 inches tall.
- plt.bar() draws the bars using your category names as x-values and revenue totals as heights.
- color=['#2196F3', '#4CAF50'] assigns a blue color to the first bar and green to the second.
- plt.title(), plt.xlabel(), and plt.ylabel() add readable labels so anyone viewing the chart knows what it shows.
- plt.tight_layout() prevents labels from being cut off at the edges.
- Run the cell by pressing the play button or pressing Shift+Enter.
- You should see a bar chart appear directly below the cell with two colored bars. The Electronics bar should be noticeably taller than Accessories.
Don't see a chart?
- Make sure you ran all previous cells first (Cells 1 through 6). The bar chart depends on category_revenue which is created in Cell 6.
- Check that plt.show() is the last line. Without it, Colab may not render the chart.
- If you see a NameError, your Cell 6 did not run successfully. Click into Cell 6 and run it again.
Why isn't my bar chart showing up in Colab?
Create a line chart of daily revenue trends
A line chart is the best choice for showing how a value changes over time. You will convert the date strings to actual date objects and then group revenue by day to see the trend.
- Create a new code cell below your bar chart and paste the following code:
# Cell 8: Line chart - Daily revenue trend
df['Date'] = pd.to_datetime(df['Date'])
daily_revenue = df.groupby('Date')['Revenue'].sum()
plt.figure(figsize=(10, 5))
plt.plot(daily_revenue.index, daily_revenue.values, marker='o', color='#FF5722', linewidth=2)
plt.title('Daily Revenue Trend', fontsize=14)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
What does this code do?
This cell prepares date-based data and draws a line chart showing how revenue changes day to day.
- pd.to_datetime(df['Date']) converts the date strings (like '2024-01-01') into proper date objects that matplotlib can plot on a time axis.
- df.groupby('Date')['Revenue'].sum() adds up all revenue for each day, since some days have multiple transactions.
- marker='o' places a circle at each data point so individual days are easy to identify.
- plt.xticks(rotation=45) tilts the date labels so they do not overlap each other.
- plt.grid(True, alpha=0.3) adds a subtle grid behind the line to make values easier to read.
- Run the cell by pressing Shift+Enter.
- You should see an orange line chart with circle markers at each data point. The x-axis shows dates and the y-axis shows revenue in dollars.
Chart looks squished or labels are cut off?
- Make sure plt.tight_layout() is included before plt.show(). This adjusts spacing so nothing gets clipped.
- If you see an error about date conversion, check that your pd.to_datetime() line comes before the groupby line.
Help me fix my matplotlib line chart in Google Colab.
Understand what makes charts presentation-ready
Both charts include formatting that makes them clear to anyone who reads them. These formatting choices are what separate a quick exploratory plot from a chart you could put in a report.
Why do titles, labels, and colors matter?
Without a title, your audience has to guess what the chart shows. Without axis labels, the numbers have no meaning. Without intentional colors, the default gray bars blend together.
Every professional chart should have three things: a descriptive title, labeled axes with units, and colors that distinguish categories. Your two charts include all three.
✔️ Awesome, I've got everything!
Great. Double check that both charts rendered correctly in your notebook before moving on.
ⓧ I'd like to double check the full code
Here is all the code you should have in your notebook so far (Cells 1 through 8):
# Cell 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Cell 2: Create the sales dataset
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03',
'2024-01-03', '2024-01-04', '2024-01-04', '2024-01-05', '2024-01-05',
'2024-01-06', '2024-01-06', '2024-01-07', '2024-01-07', '2024-01-08',
'2024-01-08', '2024-01-09', '2024-01-09', '2024-01-10', '2024-01-10'],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Laptop',
'Headphones', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Electronics',
'Accessories', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'],
'Quantity': [2, 5, 3, 1, 1, 4, 6, 2, 2, 3,
1, 4, 5, 1, 2, 3, 7, 3, 2, 5],
'Price': [999.99, 29.99, 79.99, 349.99, 999.99,
59.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99]
}
df = pd.DataFrame(data)
print("Dataset created successfully!")
print(f"Shape: {df.shape[0]} rows, {df.shape[1]} columns")
# Cell 3: Explore the data
print("First 5 rows:")
print(df.head())
print("\nDataset info:")
print(df.info())
print("\nColumn types:")
print(df.dtypes)
# Cell 4: Add a Revenue column and generate summary statistics
df['Revenue'] = df['Quantity'] * df['Price']
print("Summary statistics:")
print(df.describe())
# Cell 5: Calculate key business metrics
total_revenue = df['Revenue'].sum()
avg_order_value = df['Revenue'].mean()
total_transactions = len(df)
print(f"\nTotal Revenue: ${total_revenue:,.2f}")
print(f"Average Order Value: ${avg_order_value:,.2f}")
print(f"Total Transactions: {total_transactions}")
# Cell 6: Group by category
category_revenue = df.groupby('Category')['Revenue'].sum()
print("\nRevenue by Category:")
print(category_revenue)
# Cell 7: Bar chart - Revenue by Category
plt.figure(figsize=(8, 5))
plt.bar(category_revenue.index, category_revenue.values, color=['#2196F3', '#4CAF50'])
plt.title('Total Revenue by Product Category', fontsize=14)
plt.xlabel('Category', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.tight_layout()
plt.show()
# Cell 8: Line chart - Daily revenue trend
df['Date'] = pd.to_datetime(df['Date'])
daily_revenue = df.groupby('Date')['Revenue'].sum()
plt.figure(figsize=(10, 5))
plt.plot(daily_revenue.index, daily_revenue.values, marker='o', color='#FF5722', linewidth=2)
plt.title('Daily Revenue Trend', fontsize=14)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Your data now has a visual story. Next up, you will save your key findings to a file so you can share them outside the notebook.
Save Your Results
Your charts tell a compelling visual story about the sales data. Now it's time to save the key numbers so you can share them outside of this notebook.
In this step, you'll package your most important findings into a clean summary and export it as a CSV file. You'll also add a markdown cell that documents your conclusions.
In this step, get ready to:
- Create a summary DataFrame and save it as a CSV file.
- Add a markdown cell documenting your key business insights.
Create a summary DataFrame and export it to CSV
Throughout this project, you calculated key metrics like total revenue, average order value, and transaction count. Right now those values only exist as variables in memory. If you close the notebook, they disappear.
A CSV file stores your results in a format that any spreadsheet tool (Excel, Google Sheets) can open. This makes sharing easy.
- Create a new code cell below your line chart cell.
- Add the following code to build a summary DataFrame and save it as a CSV file:
# Cell 9: Save results to CSV
summary = pd.DataFrame({
'Metric': ['Total Revenue', 'Average Order Value', 'Total Transactions'],
'Value': [f'${total_revenue:,.2f}', f'${avg_order_value:,.2f}', total_transactions]
})
summary.to_csv('sales_summary.csv', index=False)
print("Summary saved to 'sales_summary.csv'!")
print(summary)
What does this code do?
This cell packages your three key metrics into a new DataFrame with two columns: Metric (the label) and Value (the number).
The .to_csv() method writes the DataFrame to a file called sales_summary.csv. The index=False argument prevents pandas from adding an extra row-number column to the file.
- Run the cell by pressing the play button or pressing Shift+Enter.
- You should see a confirmation message and a table with three rows showing Total Revenue, Average Order Value, and Total Transactions.
Seeing a NameError?
If you see an error mentioning that total_revenue or avg_order_value is not defined, go back and run Cell 5 first. Colab cells must be run in order for variables to exist in memory.
You can re-run all cells from the top by clicking Runtime in the menu bar, then selecting Run all.
help me fix a NameError in my Colab notebook
✔️ Awesome, I've got everything!
Great. Double check you've run all cells in order from top to bottom.
ⓧ I'd like to double check the full code
Here is the complete notebook code from Cell 1 through Cell 9:
# Cell 1: Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Cell 2: Create the sales dataset
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03',
'2024-01-03', '2024-01-04', '2024-01-04', '2024-01-05', '2024-01-05',
'2024-01-06', '2024-01-06', '2024-01-07', '2024-01-07', '2024-01-08',
'2024-01-08', '2024-01-09', '2024-01-09', '2024-01-10', '2024-01-10'],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Laptop',
'Headphones', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics', 'Electronics',
'Accessories', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories',
'Electronics', 'Accessories', 'Accessories', 'Electronics', 'Accessories'],
'Quantity': [2, 5, 3, 1, 1, 4, 6, 2, 2, 3,
1, 4, 5, 1, 2, 3, 7, 3, 2, 5],
'Price': [999.99, 29.99, 79.99, 349.99, 999.99,
59.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99,
999.99, 29.99, 79.99, 349.99, 59.99]
}
df = pd.DataFrame(data)
print("Dataset created successfully!")
print(f"Shape: {df.shape[0]} rows, {df.shape[1]} columns")
# Cell 3: Explore the data
print("First 5 rows:")
print(df.head())
print("\nDataset info:")
print(df.info())
print("\nColumn types:")
print(df.dtypes)
# Cell 4: Add a Revenue column and generate summary statistics
df['Revenue'] = df['Quantity'] * df['Price']
print("Summary statistics:")
print(df.describe())
# Cell 5: Calculate key business metrics
total_revenue = df['Revenue'].sum()
avg_order_value = df['Revenue'].mean()
total_transactions = len(df)
print(f"\nTotal Revenue: ${total_revenue:,.2f}")
print(f"Average Order Value: ${avg_order_value:,.2f}")
print(f"Total Transactions: {total_transactions}")
# Cell 6: Group by category
category_revenue = df.groupby('Category')['Revenue'].sum()
print("\nRevenue by Category:")
print(category_revenue)
# Cell 7: Bar chart - Revenue by Category
plt.figure(figsize=(8, 5))
plt.bar(category_revenue.index, category_revenue.values, color=['#2196F3', '#4CAF50'])
plt.title('Total Revenue by Product Category', fontsize=14)
plt.xlabel('Category', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.tight_layout()
plt.show()
# Cell 8: Line chart - Daily revenue trend
df['Date'] = pd.to_datetime(df['Date'])
daily_revenue = df.groupby('Date')['Revenue'].sum()
plt.figure(figsize=(10, 5))
plt.plot(daily_revenue.index, daily_revenue.values, marker='o', color='#FF5722', linewidth=2)
plt.title('Daily Revenue Trend', fontsize=14)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Revenue ($)', fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Cell 9: Save results to CSV
summary = pd.DataFrame({
'Metric': ['Total Revenue', 'Average Order Value', 'Total Transactions'],
'Value': [f'${total_revenue:,.2f}', f'${avg_order_value:,.2f}', total_transactions]
})
summary.to_csv('sales_summary.csv', index=False)
print("Summary saved to 'sales_summary.csv'!")
print(summary)
Add a markdown cell summarizing your insights
A notebook is more than just code. Adding written context helps anyone (including future you) understand what the data revealed.
- Click the + Text button in the toolbar at the top of your notebook to create a new markdown cell below your last code cell.
- Type a heading and a few bullet points summarizing your key findings. Here is an example:
## Key Business Insights
- Electronics generated significantly more revenue than Accessories
- Revenue peaked on certain days, suggesting potential patterns in buying behavior
- The average order value reflects a mix of high-ticket items (Laptops, Monitors) and low-cost accessories
Why add markdown cells?
Markdown cells turn your notebook into a readable report. Hiring managers and collaborators look for notebooks that explain the "so what" behind the numbers, not just raw code output.
You can customize the text to reflect whatever patterns you noticed in your own analysis.
- Click outside the markdown cell or press Shift+Enter to render it.
- You should see your heading and bullet points displayed with nice formatting instead of raw text.
Markdown not rendering?
Make sure you clicked + Text (not + Code). Text cells render markdown. Code cells try to execute it as Python and will throw a syntax error.
If you accidentally created a code cell, delete it and create a new text cell instead.
help me add a markdown cell in Google Colab
Your analysis is complete and saved. If you're up for a challenge, the Secret Mission will take your notebook to the next level with a pie chart and a polished PDF export.
Secret mission
Add a Pie Chart and Export a PDF Report
Your analysis notebook is complete, but a professional data scientist goes further. Can you add a pie chart showing revenue distribution and export your entire notebook as a polished PDF report?
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely in Google Colab, so there are no ongoing costs or cloud resources to worry about. Decide whether to keep your notebook, pause it, or delete it entirely.
Resources you used:
- Google Colab notebook ("Sales Data Analysis") stored in your Google Drive.
- The sales_summary.csv file generated in the Colab runtime.
Keep everything running
No action needed. Choose this if you want to keep building on your notebook or reference it later.
- Your notebook stays in Google Drive under the Colab Notebooks folder.
- The runtime disconnects automatically after inactivity, but your notebook code and markdown cells are saved.
- The sales_summary.csv file only exists while the runtime is active. It disappears when the runtime disconnects.
Pause - I'll come back to this later
Disconnect the runtime to free up resources. Your notebook code stays saved in Google Drive.
- In your Colab notebook, click Runtime in the top menu bar.
- Click Disconnect and delete runtime.
- Your code cells and markdown remain saved. When you return, click Runtime > Run all to re-execute everything.
Delete - I don't want to use this again
Remove your notebook from Google Drive entirely. This cannot be undone after you empty the trash.
- Open Google Drive at drive.google.com.
- Navigate to the Colab Notebooks folder.
- Right-click the Sales Data Analysis notebook and select Move to trash.
- To permanently delete, open Trash in the left sidebar and click Empty trash.
- The sales_summary.csv file lives only in the Colab runtime. It is automatically deleted when the runtime disconnects.
Nice Work!
Nice Work!
Congratulations! You just completed your first data science project. You built a complete data analysis notebook that loads, explores, analyzes, and visualizes real sales data using Python.
You've learned how to:
- Loaded and explored a sales dataset using pandas DataFrames, including df.head(), df.info(), and df.describe() for summary statistics.
- Calculated key business metrics and grouped insights using .groupby() to find revenue per product category.
- Created a bar chart and line chart using matplotlib to visualize revenue data and trends over time.
- Secret Mission: Created a pie chart showing revenue distribution and exported your notebook as a professional PDF report.
Ready to quiz yourself?