Pandas E-commerce Data Analysis Practice
This section uses a complete e-commerce data analysis case to comprehensively apply various Pandas features for data analysis.
Case Overview
Analyze e-commerce platform order data, including sales trends, product performance, customer analysis, and other dimensions.
Data Preparation
Example
import pandas as pd
import numpy as np
# Simulate e-commerce order data
np.random.seed(42)
n_orders = 1000
orders = pd.DataFrame({
"Order ID": range(1, n_orders + 1),
"Customer ID": np.random.randint(100, 200, n_orders),
"Product ID": np.random.randint(1, 20, n_orders),
"Order Date": pd.date_range("2024-01-01", periods=n_orders, freq="30min"),
"Quantity": np.random.randint(1, 5, n_orders),
"Unit Price": np.random.uniform(10, 500, n_orders).round(2)
})
# Calculate order amount
orders["Order Amount"] = (orders["Quantity"] * orders["Unit Price"]).round(2)
print("Order data overview:")
print(orders.head(10))
print(f"\nData volume: {len(orders)} records")
import numpy as np
# Simulate e-commerce order data
np.random.seed(42)
n_orders = 1000
orders = pd.DataFrame({
"Order ID": range(1, n_orders + 1),
"Customer ID": np.random.randint(100, 200, n_orders),
"Product ID": np.random.randint(1, 20, n_orders),
"Order Date": pd.date_range("2024-01-01", periods=n_orders, freq="30min"),
"Quantity": np.random.randint(1, 5, n_orders),
"Unit Price": np.random.uniform(10, 500, n_orders).round(2)
})
# Calculate order amount
orders["Order Amount"] = (orders["Quantity"] * orders["Unit Price"]).round(2)
print("Order data overview:")
print(orders.head(10))
print(f"\nData volume: {len(orders)} records")
Data Preprocessing
Example
# Extract date features
orders["Date"] = orders["Order Date"].dt.date
orders["Hour"] = orders["Order Date"].dt.hour
orders["Weekday"] = orders["Order Date"].dt.day_name()
orders["Month"] = orders["Order Date"].dt.month
print("After adding time features:")
print(orders.head())
print()
# Missing value check
print("Missing value check:")
print(orders.isnull().sum())
orders["Date"] = orders["Order Date"].dt.date
orders["Hour"] = orders["Order Date"].dt.hour
orders["Weekday"] = orders["Order Date"].dt.day_name()
orders["Month"] = orders["Order Date"].dt.month
print("After adding time features:")
print(orders.head())
print()
# Missing value check
print("Missing value check:")
print(orders.isnull().sum())
Sales Analysis
Overall Sales Situation
Example
# Overall sales metrics
print("=== Overall Sales Situation ===\n")
print(f"Total orders: {len(orders):,}")
print(f"Total sales: ¥{orders['Order Amount'].sum():,.2f}")
print(f"Average order amount: ¥{orders['Order Amount'].mean():,.2f}")
print(f"Median order amount: ¥{orders['Order Amount'].median():,.2f}")
print()
# Monthly statistics
monthly = orders.groupby("Month").agg({
"Order ID": "count",
"Order Amount": "sum",
"Customer ID": "nunique"
}).rename(columns={
"Order ID": "Order Count",
"Order Amount": "Sales Amount",
"Customer ID": "Customer Count"
})
print("Monthly sales trend:")
print(monthly)
print("=== Overall Sales Situation ===\n")
print(f"Total orders: {len(orders):,}")
print(f"Total sales: ¥{orders['Order Amount'].sum():,.2f}")
print(f"Average order amount: ¥{orders['Order Amount'].mean():,.2f}")
print(f"Median order amount: ¥{orders['Order Amount'].median():,.2f}")
print()
# Monthly statistics
monthly = orders.groupby("Month").agg({
"Order ID": "count",
"Order Amount": "sum",
"Customer ID": "nunique"
}).rename(columns={
"Order ID": "Order Count",
"Order Amount": "Sales Amount",
"Customer ID": "Customer Count"
})
print("Monthly sales trend:")
print(monthly)
Product Analysis
Example
# Product sales ranking
product_sales = orders.groupby("Product ID").agg({
"Order ID": "count",
"Quantity": "sum",
"Order Amount": "sum"
}).rename(columns={
"Order ID": "Order Count",
"Quantity": "Sales Volume",
"Order Amount": "Sales Amount"
}).sort_values("Sales Amount", ascending=False)
print("=== Top 10 Product Sales Ranking ===\n")
print(product_sales.head(10))
print()
# Best-selling product
print(f"Best-selling product: Product {product_sales.index)
print(f"Sales amount: ¥{product_sales.iloc)
product_sales = orders.groupby("Product ID").agg({
"Order ID": "count",
"Quantity": "sum",
"Order Amount": "sum"
}).rename(columns={
"Order ID": "Order Count",
"Quantity": "Sales Volume",
"Order Amount": "Sales Amount"
}).sort_values("Sales Amount", ascending=False)
print("=== Top 10 Product Sales Ranking ===\n")
print(product_sales.head(10))
print()
# Best-selling product
print(f"Best-selling product: Product {product_sales.index)
print(f"Sales amount: ¥{product_sales.iloc)
Customer Analysis
Example
# Customer spending analysis
customer_sales = orders.groupby("Customer ID").agg({
"Order ID": "count",
"Order Amount": "sum"
}).rename(columns={
"Order ID": "Order Count",
"Order Amount": "Total Spending"
})
print("=== Customer Analysis ===\n")
print(f"Active customer count: {len(customer_sales)}")
print(f"Average orders per customer: {customer_sales['Order Count'].mean():.1f}")
print(f"Average spending per customer: ¥{customer_sales['Total Spending'].mean():,.2f}")
print()
# Customer segmentation
customer_sales["Segment"] = pd.cut(
customer_sales["Total Spending"],
bins=[0, 1000, 5000, 10000, float("inf")],
labels=["Regular", "Silver", "Gold", "VIP"]
)
print("Customer segment statistics:")
print(customer_sales["Segment"].value_counts())
customer_sales = orders.groupby("Customer ID").agg({
"Order ID": "count",
"Order Amount": "sum"
}).rename(columns={
"Order ID": "Order Count",
"Order Amount": "Total Spending"
})
print("=== Customer Analysis ===\n")
print(f"Active customer count: {len(customer_sales)}")
print(f"Average orders per customer: {customer_sales['Order Count'].mean():.1f}")
print(f"Average spending per customer: ¥{customer_sales['Total Spending'].mean():,.2f}")
print()
# Customer segmentation
customer_sales["Segment"] = pd.cut(
customer_sales["Total Spending"],
bins=[0, 1000, 5000, 10000, float("inf")],
labels=["Regular", "Silver", "Gold", "VIP"]
)
print("Customer segment statistics:")
print(customer_sales["Segment"].value_counts())
Time Analysis
Example
# Analysis by time period
hourly = orders.groupby("Hour")["Order Amount"].sum()
print("=== Time Period Sales Analysis ===\n")
print(f"Peak sales hour: {hourly.idxmax()} o'clock")
print(f"Sales amount during that period: ¥{hourly.max():,.2f}")
print()
# Analysis by weekday
weekday = orders.groupby("Weekday")["Order Amount"].sum().reindex([
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
])
print("Weekday sales:")
for day, amount in weekday.items():
print(f"{day}: ¥{amount:,.2f}")
hourly = orders.groupby("Hour")["Order Amount"].sum()
print("=== Time Period Sales Analysis ===\n")
print(f"Peak sales hour: {hourly.idxmax()} o'clock")
print(f"Sales amount during that period: ¥{hourly.max():,.2f}")
print()
# Analysis by weekday
weekday = orders.groupby("Weekday")["Order Amount"].sum().reindex([
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
])
print("Weekday sales:")
for day, amount in weekday.items():
print(f"{day}: ¥{amount:,.2f}")
Analysis Summary
Example
print("""
=== E-commerce Data Analysis Summary ===
1. Sales Overview
- Total orders: {0}
- Total sales: ¥{1:,.2f}
- Average order value: ¥{2:.2f}
2. Product Performance
- Best-selling product: Product {3}
- Product sales distribution is uneven, with top products contributing substantial revenue
3. Customer Insights
- Active customers: {4} people
- Recommend prioritizing retention of high-value customers
4. Time Patterns
- Sales peak around {5} o'clock
- Marketing strategies can be adjusted based on peak periods
5. Optimization Suggestions
- 1) Increase inventory and promotion for best-selling products
- 2) Provide personalized services to high-value customers
- 3) Increase customer service staffing during peak sales hours
""".format(
len(orders),
orders["Order Amount"].sum(),
orders["Order Amount"].mean(),
product_sales.index[0],
len(customer_sales),
hourly.idxmax()
))
=== E-commerce Data Analysis Summary ===
1. Sales Overview
- Total orders: {0}
- Total sales: ¥{1:,.2f}
- Average order value: ¥{2:.2f}
2. Product Performance
- Best-selling product: Product {3}
- Product sales distribution is uneven, with top products contributing substantial revenue
3. Customer Insights
- Active customers: {4} people
- Recommend prioritizing retention of high-value customers
4. Time Patterns
- Sales peak around {5} o'clock
- Marketing strategies can be adjusted based on peak periods
5. Optimization Suggestions
- 1) Increase inventory and promotion for best-selling products
- 2) Provide personalized services to high-value customers
- 3) Increase customer service staffing during peak sales hours
""".format(
len(orders),
orders["Order Amount"].sum(),
orders["Order Amount"].mean(),
product_sales.index[0],
len(customer_sales),
hourly.idxmax()
))