📊 Building Enterprise Data Analysis Projects in Python
An enterprise Data Analysis Project moves through a rigorous computational lifecycle: ingesting messy raw telemetry or transactional streams, executing deterministic data cleaning (null handling, schema validation, and outlier clipping), performing Exploratory Data Analysis (EDA), running multi-attribute aggregations, and generating actionable business intelligence. Powered by Pandas, NumPy, and statistical modules, this guide breaks down real-time implementation patterns for production data pipelines.
import pandas as pd
# Raw transactional payload representing incoming store orders
raw_data = {
"Order_ID": ["ORD-1001", "ORD-1002", "ORD-1003", "ORD-1004"],
"Tx_Date": ["2026-10-01", "2026-10-02", "2026-10-02", "2026-10-03"],
"Customer_City": [" Pune ", "mumbai", "PUNE", " Bengaluru"],
"Amount_Paid": ["2499.00", "1450.50", "3999.00", "890.00"],
"Payment_Status": ["SUCCESS", "SUCCESS", "FAILED", "SUCCESS"]
}
df = pd.DataFrame(raw_data)
# 1. Standardize column headers to lowercase
df.columns = [c.lower() for c in df.columns]
# 2. Type casting: Datetime parsing and float precision
df["tx_date"] = pd.to_datetime(df["tx_date"])
df["amount_paid"] = df["amount_paid"].astype(float)
# 3. Text cleaning: Strip whitespace and capitalize city names uniformly
df["customer_city"] = df["customer_city"].str.strip().str.title()
print("Cleaned Ingestion DataFrame:")
print(df)
print("\nData Schema Types:\n", df.dtypes)
import pandas as pd
import numpy as np
# Sample customer behavior dataset with null artifacts
records = pd.DataFrame({
"user_id": [201, 202, 203, 204, 205],
"category": ["Electronics", "Fashion", "Electronics", "Fashion", "Home"],
"spend_inr": [12500.0, np.nan, 8400.0, 3200.0, np.nan],
"coupon_applied": ["FESTIVE10", None, "DIWALI50", None, None]
})
print("Null Value Audit per Column:")
print(records.isnull().sum())
# 1. Fill missing categorical coupon values with a deterministic default
records["coupon_applied"] = records["coupon_applied"].fillna("NO_COUPON")
# 2. Impute missing spend values based on category group median
records["spend_inr"] = records.groupby("category")["spend_inr"].transform(
lambda grp: grp.fillna(grp.median())
)
# 3. Fallback for categories with completely missing groups
records["spend_inr"] = records["spend_inr"].fillna(records["spend_inr"].median())
print("\nRemediated Clean Dataset:")
print(records)
import pandas as pd
import numpy as np
# Transaction values containing both normal retail swipes and extreme outlier glitches
amounts = pd.Series([450.0, 620.0, 580.0, 710.0, 490.0, 680.0, 520.0, 95000.0, 25.0])
# 1. Calculate Quartiles and IQR
q1 = amounts.quantile(0.25)
q3 = amounts.quantile(0.75)
iqr = q3 - q1
lower_fence = q1 - (1.5 * iqr)
upper_fence = q3 + (1.5 * iqr)
# 2. Identify outliers beyond fences
outliers = amounts[(amounts < lower_fence) | (amounts > upper_fence)]
clean_records = amounts[(amounts >= lower_fence) & (amounts <= upper_fence)]
print(f"Q1 (25%): {q1:.1f} | Q3 (75%): {q3:.1f} | IQR: {iqr:.1f}")
print(f"Permissible Envelope: [{lower_fence:.1f} to {upper_fence:.1f}]")
print("Detected Anomalous Outliers:\n", outliers.values)
print(f"Retained Clean Observations Count: {len(clean_records)}/{len(amounts)}")
import pandas as pd
# Multi-region e-commerce sales ledger
orders = pd.DataFrame({
"region": ["West", "West", "North", "North", "South", "West", "South"],
"customer_id": [11, 12, 13, 11, 14, 15, 14],
"revenue_inr": [3500.0, 1200.0, 4800.0, 2200.0, 1850.0, 9500.0, 2100.0]
})
# Aggregate multi-dimensional KPIs per geographic region
regional_summary = orders.groupby("region").agg(
total_orders=("revenue_inr", "count"),
unique_customers=("customer_id", "nunique"),
total_revenue_inr=("revenue_inr", "sum"),
avg_order_value_inr=("revenue_inr", "mean")
).reset_index()
# Sort by gross revenue descending
regional_summary = regional_summary.sort_values(by="total_revenue_inr", ascending=False)
print("Regional Performance Scorecard:")
print(regional_summary.round(2))
import pandas as pd
# Chronological daily revenue stream
daily_sales = pd.DataFrame({
"date": pd.date_range(start="2026-10-01", periods=6, freq="D"),
"daily_revenue": [12000.0, 14500.0, 13800.0, 18200.0, 17900.0, 22500.0]
}).set_index("date")
# 1. Compute 3-day rolling moving average
daily_sales["3d_rolling_avg"] = daily_sales["daily_revenue"].rolling(window=3).mean()
# 2. Compute Day-over-Day (DoD) percentage growth rate
daily_sales["dod_growth_pct"] = daily_sales["daily_revenue"].pct_change() * 100.0
print("Timeseries Trend & Growth Matrix:")
print(daily_sales.round(2))
import pandas as pd
# Order records
df_orders = pd.DataFrame({
"order_id": ["O101", "O102", "O103", "O104"],
"customer_id": [501, 502, 501, 505],
"amount_inr": [4500.0, 1200.0, 8900.0, 3100.0]
})
# Customer demographic records
df_customers = pd.DataFrame({
"customer_id": [501, 502, 503],
"customer_name": ["Rahul Sharma", "Pooja Verma", "Amit Patil"],
"city": ["Pune", "Mumbai", "Bengaluru"]
})
# Execute left join: Retain all orders, attaching customer profile details when available
enriched_orders = pd.merge(df_orders, df_customers, on="customer_id", how="left")
# Mark guest / unregistered buyers
enriched_orders["customer_name"] = enriched_orders["customer_name"].fillna("Guest Buyer")
print("Enriched Relational Order View:")
print(enriched_orders[["order_id", "customer_id", "customer_name", "city", "amount_inr"]])
pivot_table().
import pandas as pd
sales_data = pd.DataFrame({
"department": ["Mens Wear", "Mens Wear", "Ladies Wear", "Ladies Wear", "Kids Wear", "Ladies Wear"],
"payment_mode": ["UPI", "Credit Card", "UPI", "Net Banking", "UPI", "Credit Card"],
"amount_inr": [2400.0, 5200.0, 3800.0, 4100.0, 1800.0, 6500.0]
})
# Pivot matrix: Rows = Department, Columns = Payment Mode, Values = Total Amount
pivot_matrix = pd.pivot_table(
sales_data,
values="amount_inr",
index="department",
columns="payment_mode",
aggfunc="sum",
fill_value=0.0,
margins=True,
margins_name="Total Gross"
)
print("Department x Payment Mode Pivot Matrix (INR):")
print(pivot_matrix)
import pandas as pd
# Web traffic and conversion telemetry
web_telemetry = pd.DataFrame({
"session_time_sec": [45, 120, 310, 480, 85, 210, 550],
"pages_viewed": [1, 3, 7, 10, 2, 5, 12],
"bounce_rate": [0.95, 0.45, 0.15, 0.05, 0.80, 0.30, 0.02],
"order_placed": [0, 0, 1, 1, 0, 1, 1]
})
# Compute Pearson correlation matrix (-1.0 to +1.0)
corr_matrix = web_telemetry.corr(method="pearson")
print("Correlation Matrix with Order Conversion:")
print(corr_matrix["order_placed"].sort_values(ascending=False).round(3))
import pandas as pd
# Snapshot of customer purchase histories
rfm_df = pd.DataFrame({
"customer_id": ["C101", "C102", "C103", "C104"],
"days_since_last_order": [5, 45, 180, 8],
"total_orders_count": [32, 12, 1, 28],
"lifetime_spend_inr": [145000.0, 38000.0, 2500.0, 98000.0]
})
# Assign segmentation tags based on business thresholds
def assign_rfm_persona(row: pd.Series) -> str:
if row["days_since_last_order"] <= 15 and row["total_orders_count"] >= 25:
return "VIP Champion"
elif row["days_since_last_order"] <= 60 and row["total_orders_count"] >= 10:
return "Loyal Regular"
elif row["days_since_last_order"] > 120:
return "Churn Risk Lead"
return "Standard Shopper"
rfm_df["segment"] = rfm_df.apply(assign_rfm_persona, axis=1)
print("RFM Customer Segmentation Output:")
print(rfm_df[["customer_id", "days_since_last_order", "total_orders_count", "lifetime_spend_inr", "segment"]])
import pandas as pd
# Monthly operations ledger
ops_df = pd.DataFrame({
"order_id": [f"O-{i}" for i in range(1, 11)],
"is_successful": [1, 1, 1, 0, 1, 1, 1, 1, 0, 1],
"net_amount": [2500, 3100, 4200, 1800, 9500, 1200, 3400, 4800, 2900, 5600]
})
def generate_kpi_dashboard(df: pd.DataFrame) -> dict:
total_attempts = len(df)
successful_tx = df[df["is_successful"] == 1]
total_volume_inr = successful_tx["net_amount"].sum()
avg_ticket_size = successful_tx["net_amount"].mean()
success_rate_pct = (len(successful_tx) / total_attempts) * 100.0
return {
"total_attempted_orders": total_attempts,
"completed_orders": len(successful_tx),
"success_rate": f"{success_rate_pct:.1f}%",
"gross_realized_revenue": f"₹{total_volume_inr:,.2f}",
"average_order_value": f"₹{avg_ticket_size:,.2f}"
}
kpi_report = generate_kpi_dashboard(ops_df)
print("Monthly Executive KPI Report:")
for kpi, value in kpi_report.items():
print(f" {kpi.replace('_', ' ').title():28s}: {value}")