0 / 8 activities
APPLIED DATA ANALYTICS

Pivot data analysis in Python — 10 Practical Steps to Better Decisions

Use Pivot data analysis in Python to compare morning and evening parcel dispatches, check which handover misses the most deadlines, and make a case for the first operational review.

Data AnalyticsPython · pandasPivot tables
Start the project →
Pivot data analysis in Python showing late dispatches by depot and shift
01

The real-world scenario

Read the business brief before touching the code.

BUSINESS BRIEF

At Padma Parcel, a fictional courier in Dhaka, a parcel can miss the afternoon truck even when the packing team finishes on time. At the October operations meeting, the Dhanmondi supervisor points to a long list of late departures. A colleague at Mirpur says a larger share of their own parcels left late. Both managers want the same thing for next week: an observer at the handover desk. The operations director can release one observer for one shift.

The director gives you the complete October dispatch log for Dhanmondi, Mirpur and Uttara. Each parcel has an assigned shift, a promised cutoff and a recorded departure. Both timestamps use Dhaka local time. A departure at the cutoff meets the promise. Depot teams handle different volumes, so a high number of missed cutoffs and a high percentage of missed cutoffs may tell different stories.

By Friday, name the depot and shift that recorded the greatest number of late parcels. That is where the director wants the first handover review. Also identify where an individual parcel most often departed late during October. Show enough evidence for either supervisor to repeat your comparison, and explain what an observer would need to check before anyone changes the roster.

02

Your role

YOUR ASSIGNMENT

Operations Data Analyst

You are the operations data analyst supporting the dispatch supervisors. They need a comparison they can trace back to individual parcels. Agree on the meaning of a missed cutoff, decide what one record represents, and check that every parcel can be assigned to a known depot and shift. A parcel that leaves at exactly the promised minute is an important test of your definition.

Deliver three small tables that managers can read side by side. Show the workload, the number of misses and the percentage late for each team. Reconcile your counts against the source log, identify the leaders under both measures, and write a recommendation for the observer’s first shift. Leave room for explanations that the departure log cannot settle.

03

Identify the problem

What is the core business problem, and which analytical method would you use to solve it?

Identify the business outcome, suitable technique and why you would choose it.

04

Investigate

Ask the right questions before developing your solution.

Q01What counts as a missed cutoff?

Ask dispatch staff which event closes the promise. Here it is the recorded departure of one parcel from its depot. A parcel promised by 16:15 that leaves at 16:15 meets its cutoff. At 16:16 it is late and contributes one miss. Being forty minutes late still counts as one miss for this decision. The director will choose the first observation shift by the number of missed parcels in October. Also report the percentage late within each shift so a small team with frequent misses does not disappear behind a busier team’s larger count.

Q02Can each row be assigned to one team?

The parcel ID identifies one completed dispatch. A second row with the same ID could represent a repeated scan, so stop and investigate it before counting. Read the two timestamp columns as dates and times. Compare them on the same local clock and keep their dates so a departure after midnight can be interpreted correctly. Use the recorded shift assignment even if the parcel physically departed later. Check that no field is missing and that depot and shift labels come from the agreed lists. A spelling difference can split one team across two rows of a report.

Q03Why use a pivot table for this report?

Imagine drawing a blank grid with one row for each depot and two columns headed AM and PM. Place every parcel in the cell where its labels meet. A pivot table automates this sorting and applies a calculation inside each cell. One pass can count the parcel IDs. Another can add the late flags, because a true flag contributes one and a false flag contributes zero. With the same labels on both tables, you can divide matching cells. A simple reshape with pivot would need a unique depot and shift pair per input row, which this log does not have.

Q04How will we know that the rates are trustworthy?

First add the workload counts across both shifts and all depots. That total should match the number of rows in the source log. Next add all the missed parcels and compare the result with a separate count of true late flags in the original rows. For a spot check, take one cell and divide its misses by its workload. In a teaching example, four misses among twenty parcels means twenty percent late. A group with no parcels would have an undefined rate. A group with parcels and zero misses has a measured rate of zero percent.

Q05What can the observer actually do with the result?

Give the observer a depot and a shift, show how many late parcels led to that choice, and specify what to look for. The observer could follow the interval between packing and loading, note when the truck arrives, and compare scan times with departure records. Share the highest-rate cell with the other supervisor as a separate follow-up. Keep the observation window comparable when reviewing the pilot. A smaller count next week could simply reflect fewer parcels. Check volume and rate together before treating a change as an improvement in the handover process.

05

Project resources

dispatch_log.csv

CSV · 300 parcels · 5 fields · October 2026

Download dataset ↓
parcel_iddepotshiftcutoff_atdeparted_at
P0001DhanmondiAM2026-10-21 10:452026-10-21 10:31
P0002DhanmondiPM2026-10-05 16:002026-10-05 16:18
P0003UttaraAM2026-10-18 10:002026-10-18 09:41
P0004MirpurPM2026-10-02 16:152026-10-02 16:57
P0005UttaraPM2026-10-31 16:152026-10-31 16:08

Data dictionary. parcel_id identifies a dispatch. depot and shift identify its assigned team. cutoff_at is its promised departure deadline. departed_at is its recorded departure. Both timestamps use Dhaka local time.

06

Topic Lesson: Pivot data analysis in Python

Explore the topic through interactive visual learning.

TOPIC LESSON
01 / 10
FOUNDATIONS

From parcel records to a two-way table

Think of a pivot table as a way to give each question an address. The row names a depot and the column names a shift. Inside the cell sits one answer about all the parcels with those labels. The same set of addresses can hold counts, totals or percentages. In our dispatch log there are many parcels per address, so we need a rule for combining records before we can display a single number.

index = depot    columns = shift
One address per cellROW × COLUMNOne address per cellAMPMDhanmondiAM groupPM groupMirpurAM groupPM groupUttaraAM groupPM group
Key takeaway: Read a cell by naming its row, column and measure.
1 / 10 slides explored
07

Build the solution

Complete the missing Python operations and run your analysis.

Dispatch reliability by depot and shift

Fill the missing identifiers in the code. Each hint explains the intended operation. Python runs in your browser after the runtime loads.

dispatch_review.py0 / 25 filled
# Import pandas to analyze the parcel dispatch log.
import as pd
# Read the CSV and parse both timestamps so they can be compared.
log = pd.("dispatch_log.csv", parse_dates=["cutoff_at", "departed_at"])
# Check that each parcel ID appears only once.
assert log["parcel_id"]., "Repeated parcel ID"
# Require a value in every dispatch field before calculating rates.
assert log.().all().all(), "Missing dispatch field"
# Check that all depot names belong to the three expected locations.
assert log["depot"].(["Dhanmondi", "Mirpur", "Uttara"]).all(), "Unknown depot"
# Check that every shift is labeled AM or PM.
assert log[""].isin(["AM", "PM"]).all(), "Unknown shift"
# Flag a parcel as late when it departs after its cutoff time.
log["late"] = log["departed_at"].(log["cutoff_at"])
# Count parcels for each depot and shift to get the total volume.
volume = log.(index="depot", columns="shift", values="parcel_id", aggfunc="count")
# Sum the late flags to count late parcels for each depot and shift.
misses = log.pivot_table(index="depot", columns="shift", values="late", ="sum")
# Check that the volume table accounts for every parcel in the log.
assert volume.sum().sum() == (log), "Volume does not reconcile"
# Check that the late-count table accounts for every flagged parcel.
assert misses.sum().sum() == log[""].sum(), "Late count does not reconcile"
# Divide late counts by matching parcel totals and convert to percentages.
rate = misses.(volume).mul(100)
# Calculate the percentage of all parcels that departed late.
network_rate = 100 * log["late"].()
# Stack the late counts into a series indexed by depot and shift.
counts = misses.()
# Stack the late percentages into a series indexed by depot and shift.
rates = .stack()
# Find the depot and shift with the largest late count, taking the first tie.
most_late = counts.()
# Find the depot and shift with the highest late percentage, taking the first tie.
highest_rate = .idxmax()
# Calculate the selected shift’s share of all late parcels across the network.
share = 100 * counts.[most_late] / counts.sum()
# Display the parcel volume table with depots as rows and shifts as columns.
print("PARCELS", .to_string(), sep="\n")
# Display the late parcel counts for each depot and shift.
print("LATE PARCELS", .to_string(), sep="\n")
# Display the late percentages rounded to two decimal places.
print("LATE RATE (%)", rate.(2).to_string(), sep="\n")
# Print the network-wide late percentage to two decimal places.
print(f"Network late rate: {:.2f}%")
# Report the depot and shift with the largest number of late parcels and its count.
print(f"Most late: {most_late[0]} {most_late[1]} | {.loc[most_late]} parcels")
# Report the depot and shift with the highest late percentage and its rate.
print(f"Highest rate: {highest_rate[0]} {highest_rate[1]} | {.loc[highest_rate]:.2f}%")
# Print the share of all late parcels covered by reviewing the selected depot and shift.
print(f"Share of all late parcels in first review: {:.2f}%")
08

End of the lesson

Reflect on your learning experience.

How was your learning experience?

Select a rating

Recommended resource

Explore additional learning resources to deepen your understanding.

Pandas pivot table and parcel dispatch counts
UDEMY · COURSE RESOURCE

Data Analytics, Data Science, ML, DL & NLP - All in 1 Course

Explore a broader course covering Python data analysis, data preparation, visualization, statistics, SQL and machine learning.

View the complete course →