0Pricing
Pandas & NumPy Academy · Lesson

Analysis and KPI Computation

Compute monthly cohort retention, product-level revenue, and rolling 30-day active users using groupby, pivot, and rolling.

Analysis and KPI Computation is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Loading Analysis-Ready Data

With cleaning and feature engineering complete, load the analysis_ready.parquet checkpoint and begin computing KPIs. This stage is pure analysis — no more data cleaning. Having a clean, validated checkpoint lets you iterate quickly on KPI definitions without re-running the time-consuming ingestion and cleaning stages. The three KPIs to compute: monthly cohort retention, product-level revenue by category, and rolling 30-day active users.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')
print(f'Loaded: {df.shape}')
print('KPIs to compute:')
print('  1. Monthly cohort retention matrix')
print('  2. Category revenue and margin ranking')
print('  3. Rolling 30-day active users per region')

KPI 1: Monthly Revenue by Category

The first KPI is monthly revenue by category. Group by both year_month and category, sum revenue, and pivot to get categories as columns and months as rows. This pivot table is the basis of the trend line chart and the top-category bar chart in the report. Apply a 3-month rolling mean to smooth the trend and highlight seasonality.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

# Monthly revenue by category
monthly_cat = (
    df.groupby(['year_month', 'category'])['revenue']
    .sum()
    .reset_index()
    .pivot(index='year_month', columns='category', values='revenue')
    .fillna(0)
    .sort_index()
)

# 3-month rolling average
monthly_cat_smooth = monthly_cat.rolling(3, min_periods=1).mean()

print('Monthly revenue by category (head):')
print(monthly_cat.round(0).head())
print('Shape:', monthly_cat.shape)

KPI 2: Top Regions by Total Revenue

Rank regions by total revenue across the entire period. Use groupby().agg() to compute multiple statistics simultaneously: total revenue, order count, unique customers, and average order value. Sort by total revenue descending and keep the top 10. Compute the revenue share of each region relative to the grand total — this reveals concentration risk (if 80% of revenue comes from one region, the business is geographically exposed).

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

region_kpi = (
    df.groupby('region')
    .agg(
        total_revenue=('revenue', 'sum'),
        order_count=('order_id', 'nunique'),
        unique_customers=('customer_id', 'nunique'),
        avg_order_value=('revenue', 'mean')
    )
    .reset_index()
    .sort_values('total_revenue', ascending=False)
)

total = region_kpi['total_revenue'].sum()
region_kpi['revenue_share'] = (region_kpi['total_revenue'] / total).round(3)

print(region_kpi.head(10).to_string(index=False))

KPI 3: Cohort Retention Matrix

The cohort retention matrix shows what percentage of customers from each acquisition cohort made at least one purchase in each subsequent period. Compute it in three steps: (1) assign each order a 'period number' = number of months since the customer's cohort month; (2) groupby cohort and period number, count distinct customers; (3) divide by the cohort size (period 0 count) to get retention rates. Pivot to cohort × period format.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

# Compute months since cohort start
df['cohort_period'] = (
    (df['order_date'].dt.to_period('M') -
     pd.PeriodIndex(df['cohort_month'], freq='M'))
    .apply(lambda x: x.n)
)

cohort_data = (
    df.groupby(['cohort_month', 'cohort_period'])['customer_id']
    .nunique()
    .reset_index()
    .rename(columns={'customer_id': 'customers'})
)

# Pivot: rows=cohort, columns=period
cohort_pivot = cohort_data.pivot(
    index='cohort_month', columns='cohort_period', values='customers'
)

cohort_sizes = cohort_pivot[0]
retention = cohort_pivot.divide(cohort_sizes, axis=0).round(3)
print('Retention matrix (first 3 cohorts):')
print(retention.head(3))

KPI 4: Rolling 30-Day Active Users

Daily Active Users (DAU) and rolling window variants are core product KPIs. Compute the number of distinct customers who purchased in any given 30-day window. Start by computing daily unique purchasers, set the date as the index, then apply rolling('30D').apply(lambda x: x.nunique()) — but note that rolling on a DatetimeIndex requires specific aggregation. An alternative is to use a set-based rolling unique count via a custom window function.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

# Daily unique purchasers
daily = (
    df.groupby('order_date')['customer_id']
    .nunique()
    .reset_index()
    .rename(columns={'customer_id': 'daily_unique_customers'})
    .set_index('order_date')
    .sort_index()
)

# 30-day rolling sum (approximation: sum of daily unique purchasers)
# True rolling unique requires custom logic
daily['rolling_30d'] = daily['daily_unique_customers'].rolling('30D').sum()

print('Rolling 30-day active customers:')
print(daily.tail())

Product-Level Revenue Ranking

For product-level analysis, rank all product IDs by total revenue and compute their cumulative revenue share. This reveals whether revenue follows a Pareto distribution (a common finding: ~20% of products generate ~80% of revenue). Compute the cumulative revenue column with .cumsum() and find the cut-off product count where cumulative share exceeds 80%. This analysis guides decisions about product portfolio prioritisation.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

product_rev = (
    df.groupby('product_id')['revenue']
    .sum()
    .sort_values(ascending=False)
    .reset_index()
)

total_rev = product_rev['revenue'].sum()
product_rev['rev_share'] = product_rev['revenue'] / total_rev
product_rev['cumulative_share'] = product_rev['rev_share'].cumsum()

pct80_cutoff = (product_rev['cumulative_share'] <= 0.80).sum()
total_products = len(product_rev)
print(f'Top {pct80_cutoff} of {total_products} products ({pct80_cutoff/total_products:.0%}) '
      f'generate 80% of revenue (Pareto)')
print(product_rev.head())

Saving All KPI Tables

Save each KPI table to a named Parquet file in the output directory. Naming convention: kpi_{name}.parquet. This makes the visualisation stage straightforward — it reads exactly the pre-computed table it needs without recomputing anything. Also save a combined KPI summary to a CSV for easy sharing with non-technical stakeholders who may open it in Excel.

import pandas as pd

# Save all KPI tables
monthly_cat.to_parquet('output/kpi_monthly_category_revenue.parquet')
region_kpi.to_parquet('output/kpi_region_summary.parquet', index=False)
retention.to_parquet('output/kpi_cohort_retention.parquet')
daily.to_parquet('output/kpi_rolling_active_users.parquet')
product_rev.to_parquet('output/kpi_product_ranking.parquet', index=False)

# Also a CSV summary for sharing
region_kpi.to_csv('output/region_summary.csv', index=False)

print('All KPI tables saved:')
print('  kpi_monthly_category_revenue.parquet')
print('  kpi_region_summary.parquet')
print('  kpi_cohort_retention.parquet')
print('  kpi_rolling_active_users.parquet')
print('  kpi_product_ranking.parquet')

Statistical Validation of KPIs

Before finalising KPIs, run statistical checks: test whether monthly revenue growth is statistically significant using a one-sample t-test against zero growth, and check whether region revenue differences are significant using one-way ANOVA. Reporting 'top region by revenue' means more when you can confirm that the difference is unlikely due to random variation. Append p-values to the KPI tables as metadata columns.

import pandas as pd
import numpy as np
from scipy import stats

df = pd.read_parquet('output/analysis_ready.parquet')

# Is revenue growth statistically significant?
monthly_total = df.groupby('year_month')['revenue'].sum().sort_index()
month_changes = monthly_total.diff().dropna()
stat, p = stats.ttest_1samp(month_changes, popmean=0)
print(f'Monthly growth test: mean={month_changes.mean():.0f}, p={p:.4f}')
print('Significant positive trend?', month_changes.mean() > 0 and p < 0.05)

# ANOVA: do regions differ significantly?
groups = [g['revenue'].values for _, g in df.groupby('region')]
f, p_anova = stats.f_oneway(*groups)
print(f'Region ANOVA: F={f:.3f}, p={p_anova:.4f}')

Computing Month-over-Month Growth Rate

The month-over-month (MoM) growth rate is a fundamental business KPI: growth = (current - previous) / previous × 100. Use pct_change() for clean computation. A 3-month moving average of MoM growth reveals the underlying trend, smoothing out monthly volatility. Negative growth rates are just as important to highlight as positive ones — they signal periods requiring investigation.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')

monthly_total = (
    df.groupby('year_month')['revenue'].sum().sort_index()
)

growth = monthly_total.pct_change() * 100
trend = growth.rolling(3, min_periods=1).mean()

kpi_growth = pd.DataFrame({
    'revenue': monthly_total,
    'mom_growth_pct': growth.round(2),
    'trend_3m_avg': trend.round(2)
})

print(kpi_growth.tail(6))
print(f'\nBest month: {monthly_total.idxmax()} (${monthly_total.max():,.0f})')
print(f'Worst month: {monthly_total.idxmin()} (${monthly_total.min():,.0f})')

Automated Anomaly Detection

Flag anomalous months automatically: months where revenue is more than 2 standard deviations from the trailing 6-month mean. These are worth investigating — they may reflect genuine business events (a successful campaign, a data outage) or data quality issues (duplicate data loaded twice). Anomaly detection is a valuable addition to any automated pipeline dashboard and helps analysts focus their investigation on the most important time periods.

import pandas as pd
import numpy as np

df = pd.read_parquet('output/analysis_ready.parquet')
monthly = df.groupby('year_month')['revenue'].sum().sort_index()

rolling_mean = monthly.rolling(6, min_periods=3).mean()
rolling_std = monthly.rolling(6, min_periods=3).std()

anomalies = monthly[
    (monthly > rolling_mean + 2 * rolling_std) |
    (monthly < rolling_mean - 2 * rolling_std)
]
print('Anomalous months (>2 std from 6-month rolling mean):')
if len(anomalies) > 0:
    print(anomalies.round(0))
else:
    print('None detected')

KPI Summary Table

Compile a single executive summary table combining the top-level values from all KPIs: total revenue, total orders, unique customers, average order value, best region, best category, and average 30-day cohort retention at month 3. This one-table summary is the first page of the report — it gives stakeholders an immediate headline view before they dive into charts and detailed tables.

import pandas as pd

df = pd.read_parquet('output/analysis_ready.parquet')
retention = pd.read_parquet('output/kpi_cohort_retention.parquet')
region_kpi = pd.read_parquet('output/kpi_region_summary.parquet')

summary = {
    'Total Revenue': f'${df["revenue"].sum():,.0f}',
    'Total Orders': f'{df["order_id"].nunique():,}',
    'Unique Customers': f'{df["customer_id"].nunique():,}',
    'Avg Order Value': f'${df["revenue"].mean():.2f}',
    'Best Region': region_kpi.iloc[0]["region"],
    'Best Category': df.groupby("category")["revenue"].sum().idxmax(),
    'Avg Month-3 Retention': f'{retention.get(3, pd.Series([0])).mean():.1%}'
}

for k, v in summary.items():
    print(f'{k:25s}: {v}')

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this lesson you learned: groupby + pivot creates the monthly category revenue matrix and cohort retention table, rolling() computes smoothed trends and 30-day active user approximations, and statistical validation (t-test for growth, ANOVA for region differences) adds rigor to the KPI story. Next up we visualise all results in a multi-panel figure and export the final report.

Frequently asked questions

Is the “Analysis and KPI Computation” lesson free?

Yes — the full text of “Analysis and KPI Computation” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Analysis and KPI Computation”?

Compute monthly cohort retention, product-level revenue, and rolling 30-day active users using groupby, pivot, and rolling. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Analysis and KPI Computation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Project Setup and Data Ingestion
  2. Data Cleaning and Feature Engineering
  3. Analysis and KPI Computation
  4. Final Visualisation and Report Export
← Back to Pandas & NumPy Academy