Mastering E-Commerce Analytics with Just One Python Script
Introduction
E-commerce companies generate large volumes of customer and order data. Analyzing this data helps identify top-performing product categories, high-value customers, and city-level revenue. In this project, we use Python and Pandas to perform a simple but effective analysis on a sample dataset.
- Creating the Dataset
We first create two DataFrames: one for customer details and one for order details.
import pandas as pd
import numpy as np
customers = pd.DataFrame({
“Customer_ID”: [101, 102, 103, 104, 105, 106],
“Name”: [“Soham”, “Ravi”, “Aditi”, “Meera”, “Dingo”, “Kunal”],
“City”: [“Mumbai”, “Delhi”, “Pune”, “Chennai”, “Mumbai”, “Bangalore”]
})
orders = pd.DataFrame({
“Order_ID”: [1, 2, 3, 4, 5, 6, 7, 8],
“Customer_ID”: [101, 102, 103, 104, 105, 106, 102, 105],
“Product_Category”: [“Electronics”, “Fashion”, “Home”, “Electronics”, “Fashion”, “Home”, “Electronics”, “Home”],
“Order_Value”: [25000, 1500, np.nan, 18000, np.nan, 4500, 22000, 5000]
})
2. Merging the Data
We merge the two datasets to create a single view of customers and their orders.
df = pd.merge(customers, orders, on=”Customer_ID”, how=”left”)
print(df)
Get Soham Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
3. Handling Missing Values
Some orders have missing Order_Value. Instead of dropping them, we fill missing values with the average value of their product category.
df[“Order_Value”] = df.groupby(“Product_Category”)[“Order_Value”].transform(lambda x: x.fillna(x.mean()))
print(df
4. Category-Wise Sales Analysis
We calculate total revenue generated by each product category.
category_sales = df.groupby(“Product_Category”)[“Order_Value”].sum().sort_values(ascending=False)
print(category_sales)
5. City-Wise Sales Analysis
We calculate total sales generated from each city.
city_sales = df.groupby(“City”)[“Order_Value”].sum().sort_values(ascending=False)
print(city_sales)
6. Customer Spending Analysis
We identify the highest-spending customers.
customerspending = df.groupby([“Customer_ID”, “Name”])[“Order_Value”].sum().sort_values(ascending=False)
print(customerspending)
Conclusion
This project shows how Python and Pandas can be used to analyze essential e-commerce metrics. We merged datasets, filled missing values using category averages, analyzed category and city performance, and ranked customers by their spending. This workflow forms the foundation of data-driven decision making in e-commerce.




