1import pandas as pd
2import numpy as np
3
4# STEP 1: INGESTION & FIRST LOOK
5df = pd.read_csv('ecommerce_orders.csv', parse_dates=['Order_Date'])
6
7print("--- Dataset Shape ---")
8print(f"Total Transactions: {df.shape[0]:,}, Total Columns: {df.shape[1]}")
9
10print("\n--- Column Data Types & Non-Null Counts ---")
11print(df.info())
12
13print("\n--- Statistical 5-Point Summary ---")
14print(df.describe().T)
15
16# STEP 2: DATA CLEANING & AUDITING
17# Check missing percentages
18null_pct = (df.isna().sum() / len(df)) * 100
19print("\n--- Missing Data % ---\n", null_pct[null_pct > 0])
20
21# Impute missing Discount with 0 and drop rows missing Customer_ID
22df['Discount_Pct'] = df['Discount_Pct'].fillna(0)
23df = df.dropna(subset=['Customer_ID'])
24
25# Remove duplicate orders
26df = df.drop_duplicates(subset=['Order_ID'], keep='first')
27
28# STEP 3: FEATURE ENGINEERING
29# Net Revenue = (Quantity * Unit_Price) * (1 - Discount_Pct / 100)
30df['Gross_Amount'] = df['Quantity'] * df['Unit_Price']
31df['Net_Revenue'] = df['Gross_Amount'] * (1 - df['Discount_Pct'] / 100)
32df['Order_Month'] = df['Order_Date'].dt.to_period('M')
33
34# STEP 4: BUSINESS INSIGHTS & AGGREGATIONS
35# Top 5 Product Categories by Revenue
36top_categories = df.groupby('Category', as_index=False).agg(
37 Total_Revenue=pd.NamedAgg('Net_Revenue', 'sum'),
38 Total_Units=pd.NamedAgg('Quantity', 'sum'),
39 Avg_Order_Value=pd.NamedAgg('Net_Revenue', 'mean'),
40 Order_Count=pd.NamedAgg('Order_ID', 'count')
41).sort_values(by='Total_Revenue', ascending=False)
42
43print("\n--- Top Categories by Revenue ---\n", top_categories)
44
45# Monthly Revenue Trend
46monthly_trend = df.groupby('Order_Month')['Net_Revenue'].sum()
47print("\n--- Monthly Revenue Trend ---\n", monthly_trend)