Use pd.crosstab(..., normalize="index") to calculate percentages within each row of a category table. For a delivery report with channels as rows, each percentage uses the number of deliveries in its own channel.

Our six fictional deliveries include three on-time Web deliveries out of four, or 75%, and one on-time Store delivery out of two, or 50%. Keep the count table beside the percentages so the different denominators remain visible.

Within Web, three of four deliveries are on time (75%) and one is late (25%). Within Store, one of two is on time (50%) and one is late (50%). Both bars represent their own channel total.
Web uses four recorded deliveries as its denominator; Store uses two. Each bar spans 100% of its own channel. The delivery records are fictional.Credit: MathBlog

Start with six delivery records

Each row below represents one delivery. The repeated Web and On time pairs are separate deliveries, so all three belong in the count. There are no missing category labels in this example.

Original fictional delivery records
channel outcome
Web On time
Web Late
Store On time
Web On time
Store Late
Web On time

The complete code includes the data. It was executed with Python 3.11.3 and pandas 2.3.3; current pandas documentation was also reviewed.

Calculate counts and within-channel percentages

The function expects a nonempty DataFrame with uniquely named channel and outcome columns. It rejects missing labels, blank labels, and non-text values before counting. It leaves the source DataFrame unchanged.

import pandas as pd


def channel_tables(deliveries):
    if not deliveries.columns.is_unique:
        raise ValueError("Column names must be unique.")
    if deliveries.empty:
        raise ValueError("There are no deliveries to summarize.")
    for name in ["channel", "outcome"]:
        labels = deliveries[name]
        if labels.isna().any():
            raise ValueError(f"Resolve missing labels in {name}.")
        if not all(isinstance(value, str) for value in labels):
            raise ValueError(f"Use text labels in {name}.")
        if labels.str.strip().eq("").any():
            raise ValueError(f"Resolve blank labels in {name}.")

    counts = pd.crosstab(deliveries["channel"], deliveries["outcome"])
    percent = pd.crosstab(
        deliveries["channel"], deliveries["outcome"], normalize="index"
    ) * 100
    return counts, percent


deliveries = pd.DataFrame({
    "channel": ["Web", "Web", "Store", "Web", "Store", "Web"],
    "outcome": ["On time", "Late", "On time", "On time", "Late", "On time"],
})
counts, percent = channel_tables(deliveries)
print("Counts:")
print(counts.to_string())
print("Within each channel (%):")
print(percent.to_string(float_format=lambda value: f"{value:.1f}"))

Expected output:

Counts:
outcome  Late  On time
channel               
Store       1        1
Web         1        3
Within each channel (%):
outcome  Late  On time
channel               
Store    50.0     50.0
Web      25.0     75.0

The first table counts records at each channel and outcome pair. The second divides each count by its row total, then multiplies by 100. The counts show the denominator behind each percentage. The plain text labels sort alphabetically here, putting Store before Web and Late before On time.

Read the denominator beside the percentage

Web has four deliveries: one late and three on time. Its on-time percentage is \(\frac{3}{4}\times100\%=75\%\). Store has two deliveries: one late and one on time. Its on-time percentage is \(\frac{1}{2}\times100\%=50\%\).

These percentages describe the supplied records. They do not establish how either channel performs beyond this small fictional dataset. Keep the different row sizes visible when comparing the percentages.

Changing the normalization changes the question. With normalize="all", Web and On time accounts for 50% of all six deliveries: three divided by six. With normalize="columns", Web accounts for 50% of the two late deliveries. That differs from the 25% of Web deliveries that were late.

Make missing labels and absent groups explicit

A delivery without an outcome needs review before it belongs in a complete outcome report. The function raises a ValueError instead of silently excluding that record. An empty input also raises a ValueError; it does not produce a zero-percent performance report.

Matching is exact. For example, On time and on time form different categories, as do Web and Web. The blank check does not trim or standardize valid labels. Apply an explicit cleanup rule first if the source needs one, and keep the original labels when you need to trace changes.

With the default dropna=True, crosstab leaves out unused categories from categorical inputs. A channel with no recorded deliveries therefore has no row in this example. If your report must show it, add a row with a count of zero and leave its percentages undefined: there is no nonzero denominator. See how to keep zero-count categories in a pandas summary for the category-list step.

Select the records before normalizing

Select the reporting period before calculating the tables. Filtering to a month before building the tables gives that month’s within-channel percentages. Filtering afterward cannot turn a full-period denominator into a monthly one.

crosstab counts rows, not unique delivery IDs. If an import duplicated a delivery record, resolve that duplicate using an appropriate identifier before summarizing. Two genuine deliveries with the same channel and outcome should both remain.

Keep the numeric percentages unrounded for later calculations. The print statement formats them to one decimal place for display. Rounding can make displayed percentages total 99.9% or 100.1%, even when the underlying row sums to 100%.

Further reading