Analyze E-Commerce Sales Data

Clean, query, and visualize e-commerce sales data using Python and SQL.

Introduction

30 Second Summary

Every online store generates thousands of transactions. Behind those numbers are patterns that tell a business what's selling, where it's selling, and how customers prefer to pay.

In this project, you will analyze real e-commerce sales data using Python and SQL inside Google Colab. You'll clean messy data, query a database for business answers, and create visualizations that tell a story to stakeholders.

What You'll Build

You'll open your finished notebook, run a cell, and see professional charts that reveal which product categories drive the most revenue and how sales patterns shift across regions.

By the end of this project, you'll have:

  • Query your sales database with SQL queries and see instant answers to questions like "Which product category generates the most revenue?" and "How do sales vary by region?".
  • Show off professional charts (bar charts, line charts, grouped comparisons) that reveal monthly revenue trends, category performance, and regional sales patterns at a glance.
  • Share a portfolio-ready notebook with hiring managers that demonstrates the exact workflow a junior data analyst delivers in their first week.
  • Secret Mission: Add a customer segmentation analysis using payment method and region data to reveal regional payment preferences with a heatmap.

Are there any prerequisites?

All you need is a Google account. Google Colab runs entirely in your browser with Python, pandas, matplotlib, and seaborn already pre-installed. There is nothing to download or configure on your computer.

Before We Start

Before we dive in, let's lock in what you're about to build and why it matters.

Set Up Your Analysis Environment

Every data analysis project starts the same way: you need a workspace with your data loaded and ready to explore. Without a clean environment, you cannot write queries or build visualizations.

In this step, you will open Google Colab (a free, browser-based notebook from Google), import the libraries you need, and load an e-commerce sales dataset so you can see what you are working with.

In this step, get ready to:
  • Create a Google Colab notebook named "E-Commerce Sales Analysis".
  • Import pandas, sqlite3, matplotlib, and seaborn into your notebook.
  • Load an e-commerce dataset and confirm it has 9 columns of sales transactions.
Open Google Colab and create a new notebook

Google Colab is a free notebook environment that runs in your browser. It comes with Python and popular data science libraries pre-installed, so you can start analyzing data immediately.

  • Open your browser and navigate to colab.research.google.com.
  • Sign in with your Google account if prompted.
  • Click File in the top menu bar.
  • Click New notebook to create a fresh notebook.
  • Click the notebook title at the top left (it will say something like "Untitled0.ipynb").
  • Replace the title with E-Commerce Sales Analysis and press Enter.

You should see your renamed notebook open with an empty code cell ready for input.

Don't see the File menu?

Make sure you are signed into your Google account. Colab requires a Google sign-in before you can create or edit notebooks.

If the page shows a pop-up dialog instead of a blank notebook, close the dialog and use File in the top menu bar to select New notebook.

help me create a new notebook in Google Colab

Why Google Colab?

Colab eliminates all setup friction. You do not need to install Python, configure PATH variables, or manage virtual environments. Libraries like pandas, matplotlib, and seaborn come pre-installed.

This means you can go from zero to analyzing data in under five minutes, which is why many data teams use Colab for quick exploratory work.

Import libraries and load the dataset

Your notebook needs four libraries: pandas for data manipulation, sqlite3 for SQL queries, matplotlib for charts, and seaborn for styled visualizations.

  • Add the following code to the first cell in your notebook:
# Cell 1: Import libraries and load data
import pandas as pd
import sqlite3
import matplotlib.pyplot as plt
import seaborn as sns

# Set visualization style
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (10, 6)

# Load the dataset
url = "https://raw.githubusercontent.com/dsrscientist/dataset1/master/Online%20Sales%20Data.csv"
df = pd.read_csv(url)

# Explore raw data
print("Dataset shape:", df.shape)
print("\nFirst 5 rows:")
df.head()

What does this code do?

  • The four import lines bring in the libraries you will use throughout this project.
  • sns.set_style("whitegrid") and plt.rcParams set a clean visual style and consistent chart size for every plot you create later.
  • pd.read_csv(url) downloads the CSV directly from a public URL into a pandas DataFrame called df.
  • The print statements and df.head() give you an immediate look at the dataset's size and first few rows.

Before you run this cell, what do you think you will see? Consider that the dataset is a CSV of online marketplace transactions.

  • Run the cell by pressing Shift+Enter or clicking the play button on the left side of the cell.

You should see two things printed: a shape of (240, 9) showing 240 rows and 9 columns, followed by a table displaying the first 5 rows with columns like Transaction ID, Date, Product Category, Product Name, Units Sold, Unit Price, Total Revenue, Region, and Payment Method.

Seeing a connection error or empty DataFrame?

If you see a URLError or HTTPError, the dataset URL may be temporarily unavailable. Try running the cell again after a few seconds.

If the error persists, you can download the "Online Sales Data" CSV from Kaggle (search for "Online Sales Dataset - Popular Marketplace Data" by shreyanshverma27), then upload it to Colab using the file upload button in the left sidebar.

help me load a CSV dataset into Google Colab

Explore the raw data structure

Now that the data is loaded, you need to understand its structure before cleaning it. The info() method reveals column types and missing values, while describe() shows summary statistics for numeric columns.

  • Click the + Code button below your first cell to create a new code cell.
  • Add the following code to the new cell:
# Cell 2: Check data structure
print(df.info())
print("\nSummary statistics:")
df.describe()

What does this code do?

  • df.info() prints each column name, its data type, and how many non-null entries it has. This tells you if anything needs fixing before analysis.
  • df.describe() calculates count, mean, min, max, and percentiles for numeric columns like Units Sold, Unit Price, and Total Revenue.
  • Run the cell by pressing Shift+Enter.

You should see a summary showing 9 columns with their data types. Notice that the Date column shows as object (a string), not a proper date type. This is something you will fix in the next step.

Seeing a NameError for df?

This means Cell 1 was not run successfully. Go back to your first cell and run it again by clicking the play button. Cells must be run in order because each cell depends on variables created in previous cells.

help me fix a NameError in Google Colab

✔️ Awesome, I've got everything!

Great. Make sure both cells ran without errors and you can see the dataset output above each cell.

ⓧ I'd like to double check the full code

Here is the complete code across both cells. Compare it to what you have in your notebook:

# Cell 1: Import libraries and load data
import pandas as pd
import sqlite3
import matplotlib.pyplot as plt
import seaborn as sns

# Set visualization style
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (10, 6)

# Load the dataset
url = "https://raw.githubusercontent.com/dsrscientist/dataset1/master/Online%20Sales%20Data.csv"
df = pd.read_csv(url)

# Explore raw data
print("Dataset shape:", df.shape)
print("\nFirst 5 rows:")
df.head()
# Cell 2: Check data structure
print(df.info())
print("\nSummary statistics:")
df.describe()

Your analysis environment is ready and you have confirmed the data loaded correctly. Next up, you will clean this raw data by parsing dates and fixing column types so it is ready for SQL queries.

Clean the Data

In the previous step, you loaded your sales data and explored its structure. You noticed that the Date column is stored as plain text and the categorical columns use the generic object dtype.

Raw data is messy. If you skip cleaning, you will hit errors in later steps when you try to query dates or group by category. No analyst ships dirty data to stakeholders.

In this step, get ready to:
  • Parse the Date column into a proper datetime type so you can extract months and years.
  • Convert text columns to the efficient category dtype.
  • Check for duplicates, missing values, and create new time-based columns.
Parse dates and fix data types

Right now, pandas treats the Date column as a plain string. That means you cannot extract the month, sort by date, or do any time-based analysis. You need to convert it to a datetime type that pandas understands.

  • Create a new code cell in your notebook and add the following code to convert your column types:
# Cell 3: Clean the data
# Convert Date to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Convert categorical columns
df['Product Category'] = df['Product Category'].astype('category')
df['Region'] = df['Region'].astype('category')
df['Payment Method'] = df['Payment Method'].astype('category')

What does this code do?

pd.to_datetime() converts the Date string (like "1/1/2024") into a proper datetime object. This unlocks time-based operations like extracting the month or sorting chronologically.

The .astype('category') calls convert text columns into a memory-efficient category dtype. Instead of storing repeated strings like "Electronics" 50 times, pandas stores integer codes that reference a small lookup table of unique values.

  • Run the cell by pressing Shift+Enter.
  • Verify the types changed by typing df.dtypes in the next empty cell and running it.

You should see datetime64[ns] next to Date, and category next to Product Category, Region, and Payment Method.

Still seeing object dtype?

Make sure you ran Cell 1 (which loads the data) before running Cell 3. If df is not defined, Colab shows a NameError. Run cells in order from the top.

help me fix my data type conversions in pandas

Check for and handle data quality issues

Before you analyze data, you need to know if any rows are duplicated or missing values. You also need to extract the month from each date so you can track revenue over time in later steps.

  • Go back to your Cell 3 and add the following code below the category conversions:
# Check for duplicates and missing values
print(f"Duplicates: {df.duplicated().sum()}")
print(f"Missing values:\n{df.isnull().sum()}")

# Extract month and year for time analysis
df['Month'] = df['Date'].dt.month
df['Month_Name'] = df['Date'].dt.strftime('%B')

# Verify cleaning
print("\nCleaned dtypes:")
print(df.dtypes)

What does this code do?

  • df.duplicated().sum() counts how many rows are exact copies of another row.
  • df.isnull().sum() checks each column for missing values and reports the count.
  • df['Date'].dt.month extracts the month number (1-12) from each date into a new Month column.
  • df['Date'].dt.strftime('%B') extracts the full month name (like "January") into a Month_Name column.

Before you run this, what dtype do you expect the Date column to show in the final output?

  • Run Cell 3 again by clicking into it and pressing Shift+Enter.

You should see the duplicates count, missing values per column, and the cleaned dtypes output. The Date column now shows datetime64[ns] and the three categorical columns show category.

Why does cleaning matter here?

In Step 3, you will load this DataFrame into a SQL database and run queries that group by month. If you skip the date conversion, the Month column would not exist, and your SQL queries would fail.

The duplicates and missing-value checks confirm your data is reliable before you base business conclusions on it.

Seeing a KeyError on the Date column?

This means the column name does not match exactly. Run df.columns.tolist() to see the actual column names and check for extra spaces or different capitalization.

help me fix a KeyError when accessing a pandas column

✔️ Awesome, I've got everything!

Great. Make sure you have saved your notebook. Google Colab auto-saves, but you can confirm by checking for the checkmark next to the notebook title.

ⓧ I'd like to double check the full code

Here is the complete Cell 3 as it should appear in your notebook:

# Cell 3: Clean the data
# Convert Date to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Convert categorical columns
df['Product Category'] = df['Product Category'].astype('category')
df['Region'] = df['Region'].astype('category')
df['Payment Method'] = df['Payment Method'].astype('category')

# Check for duplicates and missing values
print(f"Duplicates: {df.duplicated().sum()}")
print(f"Missing values:\n{df.isnull().sum()}")

# Extract month and year for time analysis
df['Month'] = df['Date'].dt.month
df['Month_Name'] = df['Date'].dt.strftime('%B')

# Verify cleaning
print("\nCleaned dtypes:")
print(df.dtypes)

Your data is now clean and ready for analysis. Next up, you will load this DataFrame into a SQL database and write real queries to answer business questions about revenue, categories, and regions.

Load Data into SQL and Query It

Your data is clean, typed correctly, and ready for real analysis. Now comes the skill that appears in 72% of data analyst job postings: SQL.

In this step, you'll load your cleaned DataFrame into an in-memory SQLite database and write SQL queries that answer real business questions. These are the exact query patterns hiring managers test in interviews.

In this step, get ready to:
  • Load your cleaned data into an in-memory SQLite database.
  • Write SQL queries to answer three business questions about the sales data.
  • Store each query result as a DataFrame for visualization in the next step.
Create an in-memory SQLite database and load the data

A DataFrame is great for cleaning, but SQL gives you a structured query language for slicing data by groups, filtering, and aggregating. You'll create a temporary database that lives in memory and disappears when your session ends.

  • Click + Code at the top of your notebook to add a new cell.
  • Create an in-memory SQLite database and load your DataFrame into it by pasting this code:
# Cell 4: Load into SQLite and query
conn = sqlite3.connect(':memory:')
df.to_sql('sales', conn, index=False, if_exists='replace')

# Verify the table
test = pd.read_sql_query("SELECT * FROM sales LIMIT 5", conn)
print(test)

What does this code do?

  • sqlite3.connect(':memory:') creates a database that exists only in RAM. No files to manage, no server to run.
  • df.to_sql('sales', conn, index=False, if_exists='replace') writes your entire cleaned DataFrame into a SQL table called sales.
  • pd.read_sql_query() runs a SQL query and returns the results as a new DataFrame.
  • Run the cell by pressing Shift+Enter.
  • You should see a table with 5 rows showing familiar columns like Transaction ID, Date, Product Category, and Total Revenue.

Seeing a NameError for conn or df?

Make sure you ran all previous cells in order (Cells 1 through 3). Colab does not automatically run earlier cells when you jump ahead.

Click Runtime in the top menu, then Run all to re-execute everything from the top.

help me fix a NameError in my Colab notebook

Answer business questions with SQL

Your data is now in a SQL table. Time to query it like an analyst would in a real job. Each query answers a specific business question and stores the result in a DataFrame you'll visualize later.

  • Add a new code cell by clicking + Code.
  • Write your first business query to find total revenue by product category:
# Cell 5: SQL Query 1 - Revenue by category
query1 = """
SELECT "Product Category",
       ROUND(SUM("Total Revenue"), 2) AS total_revenue,
       COUNT(*) AS num_transactions
FROM sales
GROUP BY "Product Category"
ORDER BY total_revenue DESC
"""
revenue_by_category = pd.read_sql_query(query1, conn)
print("Revenue by Category:")
print(revenue_by_category)

What does this query do?

  • GROUP BY "Product Category" groups all rows by their category so you can aggregate within each group.
  • SUM("Total Revenue") adds up all revenue within each group. COUNT(*) counts how many transactions occurred.
  • ORDER BY total_revenue DESC sorts highest-revenue categories to the top.

This is the classic "top performers" query that analysts run first when exploring a new dataset.

Before you run this cell, predict: which product category do you think generates the most revenue?

  • Run the cell with Shift+Enter.

You should see Electronics at the top of the table with the highest total revenue.

Seeing an OperationalError about column names?

Column names with spaces (like Product Category) must be wrapped in double quotes in SQLite. Check that your query uses "Product Category" and "Total Revenue" with the quotes included.

help me fix a SQL column name error in SQLite

  • Add another new code cell by clicking + Code.
  • Write your second query to find average metrics by region:
# Cell 6: SQL Query 2 - Average metrics by region
query2 = """
SELECT Region,
       ROUND(AVG("Unit Price"), 2) AS avg_unit_price,
       ROUND(AVG("Units Sold"), 1) AS avg_units_sold,
       ROUND(SUM("Total Revenue"), 2) AS total_revenue
FROM sales
GROUP BY Region
ORDER BY total_revenue DESC
"""
metrics_by_region = pd.read_sql_query(query2, conn)
print("Metrics by Region:")
print(metrics_by_region)

What does this query do?

  • AVG("Unit Price") calculates the average price per item sold in each region.
  • AVG("Units Sold") shows how many units a typical transaction includes per region.
  • Combining AVG and SUM in one query gives you both the typical transaction profile and the overall performance per region.
  • Run the cell with Shift+Enter.
  • You should see a table with three regions (North America, Europe, Asia) showing their average unit price, average units sold, and total revenue.
  • Add one more code cell by clicking + Code.
  • Write your third query to find the monthly revenue trend:
# Cell 7: SQL Query 3 - Monthly revenue trend
query3 = """
SELECT Month,
       ROUND(SUM("Total Revenue"), 2) AS monthly_revenue
FROM sales
GROUP BY Month
ORDER BY Month
"""
monthly_revenue = pd.read_sql_query(query3, conn)
print("Monthly Revenue:")
print(monthly_revenue)

What does this query do?

This query uses the Month column you extracted during cleaning in Step 2. It sums revenue per month and sorts chronologically, giving you the shape of a time series you'll chart in the next step.

  • Run the cell with Shift+Enter.
  • You should see a table with months numbered 1 through 12 (or however many months the dataset covers) and each month's total revenue.

Getting empty results or zeros?

If monthly_revenue shows no rows, your Month column may not exist in the SQL table. This happens if you skipped the month extraction in Step 2 (the df['Month'] = df['Date'].dt.month line) or did not re-run Cell 3 before loading into SQL.

Re-run Cells 3 and 4 in order, then try this query again.

help me debug empty SQL query results in my Colab notebook

✔️ Awesome, I've got everything!

Great. Double check you've saved your notebook (Colab auto-saves, but you can press Ctrl+S or Cmd+S to be safe).

ⓧ I'd like to double check the full code

Your notebook should now have 7 cells. Scroll up and confirm each one is present in this order:

  • Cell 1: Import libraries and load data (import pandas as pd through df.head()).
  • Cell 2: Check data structure (df.info() and df.describe()).
  • Cell 3: Clean the data (datetime conversion, category dtypes, month extraction).
  • Cell 4: Load into SQLite (sqlite3.connect(':memory:') through print(test)).
  • Cell 5: SQL Query 1 (revenue by category, stored in revenue_by_category).
  • Cell 6: SQL Query 2 (metrics by region, stored in metrics_by_region).
  • Cell 7: SQL Query 3 (monthly revenue, stored in monthly_revenue).

You now have three DataFrames loaded with real business answers. Next up, you'll turn these numbers into professional charts that tell a visual story to stakeholders.

Visualize Your Findings

Your SQL queries have answered the business questions. You now have DataFrames showing revenue by category, metrics by region, and monthly trends.

Numbers in a table do not persuade stakeholders. Charts make patterns obvious at a glance, and a well-labeled chart is what gets pinned to the team dashboard. In this step, you will turn those query results into three professional visualizations using matplotlib and seaborn.

In this step, get ready to:
  • Create a bar chart showing which product categories generate the most revenue.
  • Create a line chart revealing how revenue changes month over month.
  • Create a grouped bar chart comparing revenue across regions and categories.
Create a revenue-by-category bar chart

The revenue_by_category DataFrame from your SQL query already has the data sorted by total revenue. A bar chart is the ideal way to show this ranking at a glance.

Before you run this, what do you think will happen when you call sns.barplot() on your revenue data? Which category do you expect to be tallest?

  • Create a new code cell in your notebook and paste the following code to generate your first chart:
# Cell 8: Visualization 1 - Revenue by category bar chart
fig, ax = plt.subplots(figsize=(10, 6))
sns.barplot(data=revenue_by_category, x='Product Category', y='total_revenue', ax=ax)
ax.set_title('Total Revenue by Product Category', fontsize=14, fontweight='bold')
ax.set_xlabel('Product Category', fontsize=12)
ax.set_ylabel('Total Revenue ($)', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()

What does this code do?

  • fig, ax = plt.subplots() creates a figure and axes object. The figsize=(10, 6) sets the chart dimensions in inches.
  • sns.barplot() draws vertical bars using the DataFrame columns you specify for x and y.
  • plt.xticks(rotation=45, ha='right') rotates the category labels so longer names do not overlap.
  • plt.tight_layout() adjusts spacing so titles and labels are not cut off at the edges.
  • Run the cell by pressing the play button or Shift+Enter.
  • You should see a bar chart rendered directly below the cell. Electronics should appear as the tallest bar, confirming it generates the most revenue.

Don't see a chart?

  • Make sure you ran all previous cells first. The revenue_by_category DataFrame must exist from Cell 5.
  • Check for a NameError in the output. If you see one, click Runtime > Run all to re-run every cell from the top.
  • Help me debug my bar chart code.
Create a monthly revenue trend line chart

Bar charts compare categories. Line charts reveal trends over time. Your monthly_revenue DataFrame has month numbers and revenue totals ready to plot as a time series.

  • Create a new code cell and paste the following to build a line chart with a peak annotation:
# Cell 9: Visualization 2 - Monthly revenue trend
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(monthly_revenue['Month'], monthly_revenue['monthly_revenue'], marker='o', linewidth=2, color='steelblue')
ax.set_title('Monthly Revenue Trend', fontsize=14, fontweight='bold')
ax.set_xlabel('Month', fontsize=12)
ax.set_ylabel('Revenue ($)', fontsize=12)
ax.grid(True, alpha=0.3)

# Annotate peak month
peak_idx = monthly_revenue['monthly_revenue'].idxmax()
peak_month = monthly_revenue.loc[peak_idx, 'Month']
peak_value = monthly_revenue.loc[peak_idx, 'monthly_revenue']
ax.annotate(f'Peak: ${peak_value:,.0f}', xy=(peak_month, peak_value),
            xytext=(peak_month + 0.5, peak_value + 500),
            arrowprops=dict(arrowstyle='->', color='red'),
            fontsize=11, color='red')
plt.tight_layout()
plt.show()

What does this code do?

  • ax.plot() draws a line connecting each month's revenue. The marker='o' adds dots at each data point so individual months stand out.
  • idxmax() finds the row index of the highest revenue month. You then pull the month number and dollar value from that row.
  • ax.annotate() places a label with an arrow pointing to the peak. This draws the reader's eye to the key insight without them scanning the whole chart.
  • Run the cell.
  • You should see a line chart with circular markers at each month and a red arrow pointing to the peak month with a dollar-value label.

Seeing a KeyError or empty chart?

  • A KeyError: 'monthly_revenue' means the column name does not match. Make sure your Cell 7 SQL uses AS monthly_revenue (lowercase) in the alias.
  • If the chart appears but shows no data points, check that Cell 7 ran successfully and monthly_revenue is not an empty DataFrame.
  • Help me fix my monthly revenue line chart.
Create a region-by-category comparison

Your first two charts answered single-dimension questions: which category earns the most, and how revenue changes over time. A grouped bar chart answers a two-dimensional question: how does each category perform in each region?

This final visualization also requires a new SQL query because the earlier queries did not group by both Region and Product Category together.

Before you run this cell, predict: do you think Electronics will dominate in every region, or will different regions have different top categories?

  • Create a new code cell and paste the following to query the cross-tabulated data, build the grouped chart, and close your database connection:
# Cell 10: Visualization 3 - Revenue by region and category
query4 = """
SELECT Region, "Product Category",
       ROUND(SUM("Total Revenue"), 2) AS total_revenue
FROM sales
GROUP BY Region, "Product Category"
ORDER BY total_revenue DESC
"""
region_category = pd.read_sql_query(query4, conn)

fig, ax = plt.subplots(figsize=(12, 6))
sns.barplot(data=region_category, x='Product Category', y='total_revenue', hue='Region', ax=ax)
ax.set_title('Revenue by Product Category and Region', fontsize=14, fontweight='bold')
ax.set_xlabel('Product Category', fontsize=12)
ax.set_ylabel('Total Revenue ($)', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.legend(title='Region')
plt.tight_layout()
plt.show()

print("Insight: Electronics dominates in North America while Home Appliances lead in Europe and Sports leads in Asia.")

# Close connection
conn.close()

What does this code do?

  • The SQL query groups by both Region and Product Category to get revenue for every combination (e.g., Electronics in North America, Electronics in Europe).
  • hue='Region' tells seaborn to color-code the bars by region. Each category gets a cluster of bars, one per region, side by side.
  • The print() statement adds a written insight below the chart. Analysts always pair a chart with a one-sentence takeaway.
  • conn.close() releases the in-memory SQLite database since all queries are complete.
  • Run the cell.
  • You should see a grouped bar chart with color-coded bars for each region, plus the printed insight text below it.

You now have three distinct charts rendered inline in your notebook: a bar chart, a line chart, and a grouped comparison. Each tells a different part of the sales story.

Chart missing or overlapping labels?

  • If you see a ProgrammingError about the connection being closed, you already ran conn.close() in a previous attempt. Re-run Cell 4 to recreate the connection, then re-run this cell.
  • If labels overlap or get cut off, make sure plt.tight_layout() is present before plt.show().
  • Help me fix my grouped bar chart.

✔️ Awesome, I've got everything!

Great. Double check you have three charts visible in your notebook: the category bar chart, the monthly trend line, and the region-by-category grouped bars.

ⓧ I'd like to double check the full code

Scroll through your notebook and confirm you have these cells in order:

  • Cell 1: Import libraries and load data.
  • Cell 2: Check data structure.
  • Cell 3: Clean the data (datetime conversion, category types, month extraction).
  • Cell 4: Load into SQLite and verify with a test query.
  • Cell 5: SQL Query 1 (revenue by category).
  • Cell 6: SQL Query 2 (average metrics by region).
  • Cell 7: SQL Query 3 (monthly revenue trend).
  • Cell 8: Bar chart of revenue by product category.
  • Cell 9: Line chart of monthly revenue with peak annotation.
  • Cell 10: Grouped bar chart of revenue by region and category, insight printout, and conn.close().

If any cell is missing, scroll up to the relevant substep in this project and copy the code from there.

You have a complete data analysis notebook: raw data in, cleaned data loaded into SQL, business questions answered with queries, and three professional charts telling the story. This is exactly what a junior analyst delivers in their first week. Ready to push further? The Secret Mission challenges you to add customer segmentation with a heatmap.

Secret mission

Customer Segmentation Analysis

Real analysts go beyond basic aggregations. Can you segment customers by payment method and region, visualize the patterns with a heatmap, and draw strategic business conclusions from multi-dimensional data?

Clean Up Your Resources

Clean Up Your Resources

Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely in Google Colab, so there are no ongoing costs.

Resources you used:

  • Google Colab notebook "E-Commerce Sales Analysis" (saved automatically to your Google Drive).

Keep everything running

No action needed. Choose this if you plan to revisit the notebook or share it as a portfolio piece.

  • Your notebook stays in Google Drive indefinitely at no cost.
  • You can share it with hiring managers by clicking Share in the top-right corner of the notebook.

Pause - I'll come back to this later

Download a local copy so you have a backup outside Google Drive.

  • In your Colab notebook, click File in the top menu bar.
  • Select Download, then Download .ipynb.
  • Save the file somewhere easy to find on your computer (like your Desktop).
  • The notebook also remains in your Google Drive. You can reopen it anytime at colab.research.google.com.

Delete - I don't want to use this again

Remove the notebook from your Google Drive entirely.

  • Open Google Drive at drive.google.com.
  • Navigate to the Colab Notebooks folder (this is where Colab saves notebooks by default).
  • Right-click the notebook named E-Commerce Sales Analysis and select Move to trash.
  • To permanently delete it, click Trash in the left sidebar, right-click the notebook, and select Delete forever.

Nice Work!

Nice Work!

You just completed a full data analysis workflow, from raw CSV to polished visualizations, using the same tools and techniques professional data analysts use every day.

You've learned how to:

  • Load and clean a real e-commerce dataset in Google Colab using pandas to parse dates, fix data types, and check for quality issues.
  • Build an in-memory SQLite database and write SQL queries that answer real business questions about revenue, regions, and product categories.
  • Create professional data visualizations with matplotlib and seaborn that turn numbers into a clear story for stakeholders.
  • Secret Mission: Perform a customer segmentation analysis using heatmaps to reveal regional payment preferences and draw actionable business insights.

Ready to quiz yourself?