Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Python

Building a Budget vs. Actuals Variance Report in pandas: Merging Plan and Spend Data, Calculating Variances, and Exporting a Flagged Summary to Excel

Learn how to build a complete, repeatable budget vs. actuals variance report in Python — from merging mismatched finance files and calculating variances, to flagging over-budget lines and exporting a color-coded Excel workbook stakeholders can actually use.

⚡ Practitioner21 min readNov 27, 2026Updated Nov 27, 2026
Building a Budget vs. Actuals Variance Report in pandas: Merging Plan and Spend Data, Calculating Variances, and Exporting a Flagged Summary to Excel
On this page
  • Introduction
  • Prerequisites
  • Setting Up the Dataset
  • Normalizing Before the Merge
  • Performing the Merge
  • Calculating Variances
  • Adding Flags for Over-Budget Lines
  • Building a Department-Level Summary
  • Preparing the Final Report DataFrame
  • Exporting a Formatted Excel Workbook
  • Wrapping It into a Reusable Function
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Building a Budget vs. Actuals Variance Report in pandas: Merging Plan and Spend Data, Calculating Variances, and Exporting a Flagged Summary to Excel

Introduction

Every finance team has some version of this problem: a budget spreadsheet built in January, an actuals export pulled from the ERP or accounting system at month-end, and a Friday afternoon deadline to tell leadership where the business is over or under plan. The manual version of this workflow — VLOOKUP the actuals into the budget file, calculate variance columns, apply conditional formatting, copy to email — works until it doesn't. It breaks when someone renames a cost center, when the actuals file has an extra 200 rows that didn't exist in the budget, or when you need to do it for twelve departments at once.

By the end of this lesson, you'll have a complete, repeatable Python pipeline that loads both files, merges them correctly, calculates absolute and percentage variances, flags line items that exceed your threshold, and exports a formatted Excel workbook your stakeholders can actually read. This isn't a toy example with three rows of made-up data — we'll build a realistic scenario with multiple departments, cost categories, and months, so the techniques translate directly to your actual environment.

What you'll learn:

  • How to load and normalize budget and actuals data from separate sources so they join cleanly
  • How to perform a merge that handles unmatched rows on either side (budget lines with no spend, spend lines with no budget)
  • How to calculate absolute variance, percentage variance, and remaining budget columns
  • How to apply conditional flags using vectorized logic so over-budget lines are automatically identified
  • How to export a multi-sheet Excel workbook with column formatting, freeze panes, and color-coded flag rows using openpyxl

Prerequisites

You should be comfortable with the pandas basics — loading files, working with DataFrames, and understanding indexes. If you need a refresher on loading CSV and Excel files or filtering with boolean masks, review those lessons first. You should also have a working Python environment with pandas, openpyxl, and numpy installed. If you haven't set that up yet, the environment setup guide covers it end to end.


Setting Up the Dataset

Before we write any analysis logic, we need data that looks like the real thing. In a production environment you'd load these from files your accounting system exports. Here we'll generate them programmatically so you can run this notebook from scratch.

import pandas as pd
import numpy as np
from datetime import date

# --- Budget Data ---
# Represents the annual plan, broken out by month, department, and category
budget_records = [
    # Engineering
    {"month": "2024-01", "department": "Engineering", "category": "Salaries",         "budget": 185000},
    {"month": "2024-01", "department": "Engineering", "category": "Software & Tools",  "budget": 12000},
    {"month": "2024-01", "department": "Engineering", "category": "Training",           "budget": 3500},
    {"month": "2024-01", "department": "Engineering", "category": "Travel",             "budget": 4000},
    {"month": "2024-02", "department": "Engineering", "category": "Salaries",           "budget": 185000},
    {"month": "2024-02", "department": "Engineering", "category": "Software & Tools",   "budget": 12000},
    {"month": "2024-02", "department": "Engineering", "category": "Training",            "budget": 3500},
    {"month": "2024-02", "department": "Engineering", "category": "Travel",              "budget": 2000},
    # Marketing
    {"month": "2024-01", "department": "Marketing",   "category": "Salaries",           "budget": 95000},
    {"month": "2024-01", "department": "Marketing",   "category": "Advertising",        "budget": 40000},
    {"month": "2024-01", "department": "Marketing",   "category": "Events",             "budget": 15000},
    {"month": "2024-01", "department": "Marketing",   "category": "Software & Tools",   "budget": 5500},
    {"month": "2024-02", "department": "Marketing",   "category": "Salaries",           "budget": 95000},
    {"month": "2024-02", "department": "Marketing",   "category": "Advertising",        "budget": 55000},
    {"month": "2024-02", "department": "Marketing",   "category": "Events",             "budget": 8000},
    {"month": "2024-02", "department": "Marketing",   "category": "Software & Tools",   "budget": 5500},
    # Operations
    {"month": "2024-01", "department": "Operations",  "category": "Salaries",           "budget": 72000},
    {"month": "2024-01", "department": "Operations",  "category": "Facilities",         "budget": 18000},
    {"month": "2024-01", "department": "Operations",  "category": "Supplies",           "budget": 6000},
    {"month": "2024-02", "department": "Operations",  "category": "Salaries",           "budget": 72000},
    {"month": "2024-02", "department": "Operations",  "category": "Facilities",         "budget": 18000},
    {"month": "2024-02", "department": "Operations",  "category": "Supplies",           "budget": 6000},
]

# --- Actuals Data ---
# Represents real spend pulled from the GL — note some differences intentionally baked in:
# - Marketing Advertising in Jan ran over budget
# - Engineering Travel in Feb was unspent
# - Operations has an unbudgeted "Contractor" line in Feb
actuals_records = [
    {"month": "2024-01", "dept": "Engineering",  "spend_category": "Salaries",         "actuals": 183200},
    {"month": "2024-01", "dept": "Engineering",  "spend_category": "Software & Tools",  "actuals": 11750},
    {"month": "2024-01", "dept": "Engineering",  "spend_category": "Training",          "actuals": 2900},
    {"month": "2024-01", "dept": "Engineering",  "spend_category": "Travel",            "actuals": 5820},
    {"month": "2024-02", "dept": "Engineering",  "spend_category": "Salaries",          "actuals": 185000},
    {"month": "2024-02", "dept": "Engineering",  "spend_category": "Software & Tools",  "actuals": 13400},
    {"month": "2024-02", "dept": "Engineering",  "spend_category": "Training",          "actuals": 3100},
    # Travel in Feb: zero spend (not in actuals file at all — common in real data)
    {"month": "2024-01", "dept": "Marketing",    "spend_category": "Salaries",          "actuals": 95000},
    {"month": "2024-01", "dept": "Marketing",    "spend_category": "Advertising",       "actuals": 61400},  # over!
    {"month": "2024-01", "dept": "Marketing",    "spend_category": "Events",            "actuals": 12300},
    {"month": "2024-01", "dept": "Marketing",    "spend_category": "Software & Tools",  "actuals": 5500},
    {"month": "2024-02", "dept": "Marketing",    "spend_category": "Salaries",          "actuals": 95000},
    {"month": "2024-02", "dept": "Marketing",    "spend_category": "Advertising",       "actuals": 48200},
    {"month": "2024-02", "dept": "Marketing",    "spend_category": "Events",            "actuals": 9100},
    {"month": "2024-02", "dept": "Marketing",    "spend_category": "Software & Tools",  "actuals": 5500},
    {"month": "2024-01", "dept": "Operations",   "spend_category": "Salaries",          "actuals": 71200},
    {"month": "2024-01", "dept": "Operations",   "spend_category": "Facilities",        "actuals": 18000},
    {"month": "2024-01", "dept": "Operations",   "spend_category": "Supplies",          "actuals": 5450},
    {"month": "2024-02", "dept": "Operations",   "spend_category": "Salaries",          "actuals": 72000},
    {"month": "2024-02", "dept": "Operations",   "spend_category": "Facilities",        "actuals": 19200},  # over!
    {"month": "2024-02", "dept": "Operations",   "spend_category": "Supplies",          "actuals": 5800},
    {"month": "2024-02", "dept": "Operations",   "spend_category": "Contractors",       "actuals": 8500},   # unbudgeted!
]

df_budget  = pd.DataFrame(budget_records)
df_actuals = pd.DataFrame(actuals_records)

print("Budget shape:", df_budget.shape)
print("Actuals shape:", df_actuals.shape)
print("\nBudget columns:", df_budget.columns.tolist())
print("Actuals columns:", df_actuals.columns.tolist())

Notice immediately that the two DataFrames have different column names — department vs dept, and category vs spend_category. This is completely normal. Budget files are usually owned by Finance and actuals exports come from an ERP or accounting system, and nobody ever agreed on naming conventions.

Note

In real environments you'll often also have mismatches in values: "Eng" vs "Engineering," "Software & Tools" vs "Software and Tools," trailing spaces, and inconsistent capitalization. We'll handle the column rename here, but if you're dealing with messy string values in your keys, check out text cleanup with pandas string methods before proceeding to the merge step — a bad join key will silently lose rows.


Normalizing Before the Merge

Before merging, we need the join keys to match exactly. This means consistent column names, consistent data types, and consistent values. Let's do that explicitly rather than trying to handle it inside the merge call.

# Standardize column names in actuals to match budget
df_actuals = df_actuals.rename(columns={
    "dept": "department",
    "spend_category": "category"
})

# Confirm both DataFrames now have the same key columns
join_keys = ["month", "department", "category"]
print("Budget keys:", df_budget[join_keys].dtypes)
print("Actuals keys:", df_actuals[join_keys].dtypes)
# Strip whitespace and normalize casing on all key columns
# This is a cheap insurance policy that saves debugging pain later
for col in join_keys:
    df_budget[col]  = df_budget[col].str.strip()
    df_actuals[col] = df_actuals[col].str.strip()

Now check that the values actually line up for at least one known key combination:

# Quick sanity check: find all unique departments in each source
print("Budget departments:",  sorted(df_budget["department"].unique()))
print("Actuals departments:", sorted(df_actuals["department"].unique()))

# And categories
print("Budget categories:",   sorted(df_budget["category"].unique()))
print("Actuals categories:",  sorted(df_actuals["category"].unique()))

You should see matching values for the shared categories. The actuals file has one extra: "Contractors" — no match in the budget. That's intentional and something we need to preserve, not drop.

Warning

A common mistake is to do df_budget.merge(df_actuals, on=join_keys) with the default how="inner" and then wonder why your row count dropped. An inner join silently drops any row that doesn't match in both DataFrames — which means unbudgeted spend lines disappear from your report entirely, and budgeted lines with zero actual spend also vanish. For a variance report you need an outer join so both sides are fully represented.


Performing the Merge

This is the core operation. We want every combination that exists in either the budget or the actuals to appear in our output. That's a full outer join. If you've worked with pandas merge and SQL joins before, you know this is how="outer".

df_merged = df_budget.merge(
    df_actuals,
    on=join_keys,
    how="outer",
    indicator=True   # adds a "_merge" column so we can see what matched
)

print(df_merged.shape)
print(df_merged["_merge"].value_counts())

The indicator=True argument is invaluable here. It adds a _merge column with three possible values:

  • both — the row matched in both budget and actuals (the normal case)
  • left_only — in budget but not in actuals (like Engineering Travel in Feb)
  • right_only — in actuals but not in budget (like Operations Contractors in Feb)
# Show the unmatched rows — these are your data quality signals
unmatched = df_merged[df_merged["_merge"] != "both"]
print(unmatched[["month", "department", "category", "budget", "actuals", "_merge"]])

Output should show:

  • Engineering / Travel / 2024-02: in budget (2000), no actuals → left_only
  • Operations / Contractors / 2024-02: no budget, actuals of 8500 → right_only

Key insight

These unmatched rows are features, not bugs. A left_only row (budget but no spend) might mean the spend hasn't happened yet, or someone forgot to code it properly in the GL. A right_only row (spend but no budget) is usually an alert — someone approved spending outside the plan. Both are important signals in a real variance report.

Now fill the NaN values that the outer join introduced. When there's no budget for a spend line, budget will be NaN. When there's no spend for a budget line, actuals will be NaN. We fill those with zero for calculation purposes, but we'll retain the _merge flag so the report consumer can see what's going on.

df_merged["budget"]  = df_merged["budget"].fillna(0)
df_merged["actuals"] = df_merged["actuals"].fillna(0)

Calculating Variances

With a clean merged DataFrame, the variance math is straightforward. The convention in finance is usually:

  • Variance (absolute): actuals - budget — positive means over budget, negative means under
  • Variance (%): (actuals - budget) / budget — expressed as a percentage of plan
  • Remaining budget: budget - actuals — how much headroom is left (or how deep the hole is)
# Absolute variance: positive = over budget (unfavorable for cost centers)
df_merged["variance_abs"] = df_merged["actuals"] - df_merged["budget"]

# Percentage variance: handle divide-by-zero when budget is 0
df_merged["variance_pct"] = np.where(
    df_merged["budget"] != 0,
    (df_merged["actuals"] - df_merged["budget"]) / df_merged["budget"],
    np.nan   # can't calculate % variance when there's no budget
)

# Remaining budget (inverse of absolute variance)
df_merged["remaining"] = df_merged["budget"] - df_merged["actuals"]

The np.where for percentage variance is important. When a spend line has no budget (the right_only rows), dividing by zero would produce inf or raise an error. Using np.nan there is correct — the concept of "% over budget" doesn't make sense when there was no budget. This is a vectorized approach that avoids a slow row-by-row apply(). You can read more about why this matters in writing fast pandas code.

Let's look at what we have so far:

print(df_merged[[
    "month", "department", "category",
    "budget", "actuals", "variance_abs", "variance_pct", "remaining"
]].to_string())

Adding Flags for Over-Budget Lines

A flat table of numbers is useful, but what stakeholders actually want is to know which lines need attention. We'll add two flag columns:

  1. status — a text label: "Over Budget", "On Track", "Under Budget", or "Unbudgeted Spend"
  2. flag — a boolean that's True whenever the line needs escalation (useful for filtering and formatting)

We'll define "needs attention" as either unbudgeted spend, or spending more than 5% over budget.

OVERAGE_THRESHOLD = 0.05  # 5% over budget triggers a flag

def classify_variance(row):
    """
    Classify each budget line by its variance status.
    Called via apply — acceptable here since it's label logic, not heavy math.
    """
    if row["_merge"] == "right_only":
        return "Unbudgeted Spend"
    elif row["variance_pct"] > OVERAGE_THRESHOLD:
        return "Over Budget"
    elif row["variance_pct"] < -0.10:   # more than 10% under — also worth noting
        return "Under Budget"
    else:
        return "On Track"

df_merged["status"] = df_merged.apply(classify_variance, axis=1)

Now add the boolean flag for lines that need escalation:

df_merged["flag"] = df_merged["status"].isin(["Over Budget", "Unbudgeted Spend"])

print("\nFlag summary:")
print(df_merged.groupby("status")["flag"].count())

Tip

If you'd prefer to avoid apply() entirely for performance, you can accomplish the same classification with nested np.where() calls or pd.cut(). For a small-to-medium finance report this rarely matters, but if you're running this across thousands of cost centers monthly, vectorizing the status column is worth it. See conditional column creation in pandas for vectorized alternatives.


Building a Department-Level Summary

The line-item detail is useful for the finance team. But leadership usually wants a rolled-up view: how is each department tracking against plan in total? Let's build that as a second sheet in our Excel output.

dept_summary = (
    df_merged
    .groupby(["month", "department"])
    .agg(
        total_budget=("budget", "sum"),
        total_actuals=("actuals", "sum"),
        flagged_lines=("flag", "sum"),          # count of flagged line items
        total_lines=("flag", "count")
    )
    .reset_index()
)

# Recalculate variance at the summary level
dept_summary["variance_abs"] = dept_summary["total_actuals"] - dept_summary["total_budget"]
dept_summary["variance_pct"] = np.where(
    dept_summary["total_budget"] != 0,
    (dept_summary["total_actuals"] - dept_summary["total_budget"]) / dept_summary["total_budget"],
    np.nan
)
dept_summary["flag"] = dept_summary["variance_pct"] > OVERAGE_THRESHOLD

print(dept_summary.to_string())

Notice we're recalculating variance at the summary level rather than summing the per-row percentages. Never aggregate percentages by summing them — the aggregated percentage variance must be computed from aggregated totals. This is one of the most common errors in financial reporting.

Warning

Summing percentage variances is mathematically wrong and will produce misleading numbers. If Engineering is 2% over on a $185k salary line and 15% over on a $12k software line, the department isn't "17% over budget" — it's a small dollar overage in the context of the full department budget. Always recompute rate metrics from rolled-up numerators and denominators.


Preparing the Final Report DataFrame

Before export, clean up column names and ordering so the spreadsheet looks professional without any manual work afterward.

# Rename for the detail sheet
detail_report = df_merged[[
    "month", "department", "category",
    "budget", "actuals", "variance_abs", "variance_pct",
    "remaining", "status", "flag", "_merge"
]].copy()

detail_report = detail_report.rename(columns={
    "month":        "Month",
    "department":   "Department",
    "category":     "Category",
    "budget":       "Budget",
    "actuals":      "Actuals",
    "variance_abs": "Variance ($)",
    "variance_pct": "Variance (%)",
    "remaining":    "Remaining Budget",
    "status":       "Status",
    "flag":         "Needs Attention",
    "_merge":       "Match Source"
})

# Sort: flagged lines first, then by department and month
detail_report = detail_report.sort_values(
    ["Needs Attention", "Department", "Month", "Category"],
    ascending=[False, True, True, True]
)

# Rename summary columns too
summary_report = dept_summary.rename(columns={
    "month":          "Month",
    "department":     "Department",
    "total_budget":   "Total Budget",
    "total_actuals":  "Total Actuals",
    "flagged_lines":  "Flagged Lines",
    "total_lines":    "Total Lines",
    "variance_abs":   "Variance ($)",
    "variance_pct":   "Variance (%)",
    "flag":           "Dept Flag"
})

summary_report = summary_report.sort_values(
    ["Dept Flag", "Month", "Department"],
    ascending=[False, True, True]
)

Exporting a Formatted Excel Workbook

This is where the report goes from "data" to "deliverable." We'll use openpyxl through pandas' ExcelWriter to build a two-sheet workbook: a department summary and a full line-item detail. If you want to go deeper on Excel formatting from Python, the automating Excel reports with openpyxl lesson covers the full toolkit.

from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter

# Color palette
RED_FILL   = PatternFill(start_color="FFCCCC", end_color="FFCCCC", fill_type="solid")
AMBER_FILL = PatternFill(start_color="FFE599", end_color="FFE599", fill_type="solid")
GREEN_FILL = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
HEADER_FILL = PatternFill(start_color="1F4E79", end_color="1F4E79", fill_type="solid")
HEADER_FONT = Font(color="FFFFFF", bold=True)

output_path = "budget_vs_actuals_report.xlsx"

with pd.ExcelWriter(output_path, engine="openpyxl") as writer:

    # --- Write both sheets ---
    summary_report.to_excel(writer, sheet_name="Department Summary", index=False)
    detail_report.to_excel(writer,  sheet_name="Line Item Detail",   index=False)

    wb = writer.book

    # ============================================================
    # Format the Department Summary sheet
    # ============================================================
    ws_summary = writer.sheets["Department Summary"]

    # Style the header row
    for cell in ws_summary[1]:
        cell.fill = HEADER_FILL
        cell.font = HEADER_FONT
        cell.alignment = Alignment(horizontal="center", wrap_text=True)

    # Freeze the header row
    ws_summary.freeze_panes = "A2"

    # Auto-fit column widths (approximation — openpyxl doesn't auto-fit natively)
    for col_idx, col_cells in enumerate(ws_summary.columns, 1):
        max_length = max(
            len(str(cell.value)) if cell.value is not None else 0
            for cell in col_cells
        )
        ws_summary.column_dimensions[get_column_letter(col_idx)].width = min(max_length + 4, 40)

    # Find the "Dept Flag" column index
    summary_headers = [cell.value for cell in ws_summary[1]]
    dept_flag_col   = summary_headers.index("Dept Flag") + 1
    variance_pct_col_sum = summary_headers.index("Variance (%)") + 1

    # Highlight flagged department rows and format numbers
    for row in ws_summary.iter_rows(min_row=2, max_row=ws_summary.max_row):
        is_flagged = row[dept_flag_col - 1].value
        for cell in row:
            if is_flagged:
                cell.fill = AMBER_FILL
        # Format variance % as percentage
        pct_cell = row[variance_pct_col_sum - 1]
        if isinstance(pct_cell.value, (int, float)) and pct_cell.value is not None:
            pct_cell.number_format = "0.0%"
        # Format dollar columns
        for col_name in ["Total Budget", "Total Actuals", "Variance ($)"]:
            if col_name in summary_headers:
                dollar_col = summary_headers.index(col_name)
                dollar_cell = row[dollar_col]
                dollar_cell.number_format = '#,##0'

    # ============================================================
    # Format the Line Item Detail sheet
    # ============================================================
    ws_detail = writer.sheets["Line Item Detail"]

    for cell in ws_detail[1]:
        cell.fill = HEADER_FILL
        cell.font = HEADER_FONT
        cell.alignment = Alignment(horizontal="center", wrap_text=True)

    ws_detail.freeze_panes = "A2"

    for col_idx, col_cells in enumerate(ws_detail.columns, 1):
        max_length = max(
            len(str(cell.value)) if cell.value is not None else 0
            for cell in col_cells
        )
        ws_detail.column_dimensions[get_column_letter(col_idx)].width = min(max_length + 4, 35)

    detail_headers       = [cell.value for cell in ws_detail[1]]
    needs_attn_col       = detail_headers.index("Needs Attention") + 1
    status_col           = detail_headers.index("Status") + 1
    variance_pct_col_det = detail_headers.index("Variance (%)") + 1

    for row in ws_detail.iter_rows(min_row=2, max_row=ws_detail.max_row):
        status_value   = row[status_col - 1].value
        needs_attn     = row[needs_attn_col - 1].value

        # Apply row color based on status
        if status_value == "Over Budget":
            fill = RED_FILL
        elif status_value == "Unbudgeted Spend":
            fill = AMBER_FILL
        elif status_value == "Under Budget":
            fill = GREEN_FILL
        else:
            fill = None

        if fill:
            for cell in row:
                cell.fill = fill

        # Format % column
        pct_cell = row[variance_pct_col_det - 1]
        if isinstance(pct_cell.value, (int, float)) and pct_cell.value is not None:
            pct_cell.number_format = "0.0%"

        # Format dollar columns
        for col_name in ["Budget", "Actuals", "Variance ($)", "Remaining Budget"]:
            if col_name in detail_headers:
                dollar_col  = detail_headers.index(col_name)
                dollar_cell = row[dollar_col]
                dollar_cell.number_format = '#,##0'

print(f"Report written to {output_path}")

When you open budget_vs_actuals_report.xlsx, you'll see:

  • Sheet 1 (Department Summary): Dark blue headers, amber rows for departments that are over their threshold, dollar and percentage formatting applied
  • Sheet 2 (Line Item Detail): Red rows for over-budget lines, amber for unbudgeted spend, green for significantly under-budget lines, with the flagged rows sorted to the top

Tip

If you want to go further with this workbook — adding charts, adding a cover page with run date and parameter summary, or distributing it via email automatically — the building and automating recurring reports with pandas lesson picks up exactly where this one leaves off.


Wrapping It into a Reusable Function

Right now all of this is imperative code that runs top to bottom. If you need to run this monthly, or for different parameter sets (different threshold, different output path, different month filter), you want it in a function you can call. Here's a clean version:

def build_variance_report(
    df_budget: pd.DataFrame,
    df_actuals: pd.DataFrame,
    output_path: str,
    overage_threshold: float = 0.05,
    month_filter: str = None
):
    """
    Build a Budget vs Actuals variance report and export to Excel.

    Parameters
    ----------
    df_budget : DataFrame with columns [month, department, category, budget]
    df_actuals : DataFrame with columns [month, department, category, actuals]
    output_path : file path for the Excel output
    overage_threshold : fraction over budget that triggers a flag (default 5%)
    month_filter : if provided, filter to a single month e.g. "2024-02"
    """
    # -- 1. Normalize --
    df_budget  = df_budget.copy()
    df_actuals = df_actuals.copy()

    # Standardize column names (assumes caller has aliased actuals to match budget)
    join_keys = ["month", "department", "category"]
    for col in join_keys:
        df_budget[col]  = df_budget[col].str.strip()
        df_actuals[col] = df_actuals[col].str.strip()

    if month_filter:
        df_budget  = df_budget[df_budget["month"] == month_filter]
        df_actuals = df_actuals[df_actuals["month"] == month_filter]

    # -- 2. Merge --
    merged = df_budget.merge(df_actuals, on=join_keys, how="outer", indicator=True)
    merged["budget"]  = merged["budget"].fillna(0)
    merged["actuals"] = merged["actuals"].fillna(0)

    # -- 3. Calculate variances --
    merged["variance_abs"] = merged["actuals"] - merged["budget"]
    merged["variance_pct"] = np.where(
        merged["budget"] != 0,
        merged["variance_abs"] / merged["budget"],
        np.nan
    )
    merged["remaining"] = merged["budget"] - merged["actuals"]

    # -- 4. Flag --
    def classify(row):
        if row["_merge"] == "right_only":
            return "Unbudgeted Spend"
        elif pd.isna(row["variance_pct"]):
            return "Unbudgeted Spend"
        elif row["variance_pct"] > overage_threshold:
            return "Over Budget"
        elif row["variance_pct"] < -0.10:
            return "Under Budget"
        return "On Track"

    merged["status"] = merged.apply(classify, axis=1)
    merged["flag"]   = merged["status"].isin(["Over Budget", "Unbudgeted Spend"])

    # -- 5. Summary --
    summary = (
        merged.groupby(["month", "department"])
        .agg(
            total_budget=("budget", "sum"),
            total_actuals=("actuals", "sum"),
            flagged_lines=("flag", "sum"),
            total_lines=("flag", "count")
        )
        .reset_index()
    )
    summary["variance_abs"] = summary["total_actuals"] - summary["total_budget"]
    summary["variance_pct"] = np.where(
        summary["total_budget"] != 0,
        summary["variance_abs"] / summary["total_budget"],
        np.nan
    )
    summary["dept_flag"] = summary["variance_pct"] > overage_threshold

    # -- 6. Export (abbreviated — reuse the formatting block from above) --
    # In production you'd call your formatting function here
    with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
        summary.to_excel(writer, sheet_name="Department Summary", index=False)
        merged.to_excel(writer, sheet_name="Line Item Detail",   index=False)

    print(f"Report saved: {output_path}")
    return merged, summary


# Usage
detail, summary = build_variance_report(
    df_budget=df_budget,
    df_actuals=df_actuals,
    output_path="budget_vs_actuals_jan_feb.xlsx",
    overage_threshold=0.05
)

Hands-On Exercise

Apply what you've built to a slightly messier scenario. Take the df_actuals DataFrame and introduce these problems, then see if your pipeline handles them correctly:

Step 1: Add a row to df_actuals where dept = "engineering" (lowercase) and spend_category = "Travel " (trailing space). After your normalization step, does it match the budget row correctly?

Step 2: Add a second January row for Marketing / Advertising / 2024-01 to df_actuals with a value of 5000. This simulates a duplicate journal entry. Run the merge — does your row count surprise you? Then de-duplicate using df_actuals.drop_duplicates(subset=join_keys) before merging. For a deeper look at how to diagnose these kinds of join surprises, see the article on detecting data quality issues across merged DataFrames.

Step 3: Change overage_threshold to 0.10 and regenerate the report. How many lines move from "Over Budget" to "On Track"? Does the Marketing Advertising January line still trigger a flag?

Step 4: Add a month_filter="2024-02" argument to your function call and confirm the output only contains February data on both sheets.


Common Mistakes & Troubleshooting

"My merged DataFrame has way more rows than I expected."
This almost always means duplicate keys in one or both source files. Run df_budget.duplicated(subset=join_keys).sum() and df_actuals.duplicated(subset=join_keys).sum() before merging. Even a single duplicate on one side can create a row explosion. De-duplicate or aggregate before merging.

"All my rows are left_only or right_only — nothing matched."
Your join keys have values that look the same but aren't. The usual culprits: inconsistent casing ("engineering" vs "Engineering"), trailing spaces, or different encoding for special characters (& vs &amp;). Add .str.lower().str.strip() to all key columns before merging and try again.

"My percentage variance shows inf for some rows."
You have actuals where the budget is exactly zero, and you're doing variance / budget without protection. Use the np.where(budget != 0, ..., np.nan) pattern shown above.

"The Excel file opens with dates showing as numbers."
If your month column is a string like "2024-01", it exports fine. If you've converted it to a datetime, Excel may format it unexpectedly. Keep month as a string for display columns, or format the Excel cells explicitly with number_format = "YYYY-MM".

"My department summary variances don't match what I calculated by hand."
Check whether you're filtering before or after the merge. If you filter the budget DataFrame before merging, you'll lose the right-side actuals that have no budget match in that filtered period. Filter after the merge, or at minimum understand what the filter is doing to both sides.

Tip

The indicator=True argument on merge is your best friend during troubleshooting. Never remove it during development — keep the _merge column in your intermediate outputs so you can always audit what matched and what didn't.


Summary & Next Steps

You've built a complete budget vs. actuals variance reporting pipeline from scratch. Here's what you now know how to do:

  • Normalize two data sources with different column names and potentially inconsistent values before joining them
  • Merge with an outer join so you capture both unspent budget lines and unbudgeted actual spend — the two signals that matter most
  • Use indicator=True to audit your join and surface data quality issues before they silently distort your numbers
  • Calculate variance (absolute, percentage, remaining) using vectorized operations, with proper handling for divide-by-zero cases
  • Classify and flag line items using business logic, sorting flagged rows to the top for stakeholder consumption
  • Build a rolled-up summary that recomputes rates from aggregated totals rather than averaging percentages
  • Export a formatted Excel workbook with color-coded rows, formatted number columns, freeze panes, and auto-fit widths

Where to go from here: If you want to make this report truly hands-off, the building and automating recurring reports lesson shows you how to schedule it to run and email itself on the first of each month. If your budget and actuals data lives in a database rather than flat files, reading from SQL databases into pandas covers how to pull both sources with a single connection. And if you want to extend the variance analysis to show month-over-month trend, comparing periods with shift and pct_change is the natural next step.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Python for Data Analysis

Previous

Calculating Cumulative and Rolling Metrics by Group in pandas: Running Totals, Moving Averages, and Period-to-Date Summaries with groupby and transform

Related Insights

PythonFoundation

Calculating Cumulative and Rolling Metrics by Group in pandas: Running Totals, Moving Averages, and Period-to-Date Summaries with groupby and transform

14 min
PythonExpert

Building a Product Affinity and Basket Analysis Report in pandas: Calculating Co-Purchase Rates, Lift, and Frequently Bought Together Pairs from Transaction Line Items

23 min
PythonPractitioner

Building a Sales Funnel Analysis in pandas: Calculating Stage Conversion Rates, Drop-Off Points, and Pipeline Velocity from CRM Export Data

19 min

On this page

  • Introduction
  • Prerequisites
  • Setting Up the Dataset
  • Normalizing Before the Merge
  • Performing the Merge
  • Calculating Variances
  • Adding Flags for Over-Budget Lines
  • Building a Department-Level Summary
  • Preparing the Final Report DataFrame
  • Exporting a Formatted Excel Workbook
  • Wrapping It into a Reusable Function
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps