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.
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.
Expert Problem Formulation
The director has one observation shift to allocate. The selection rule is the largest number of late parcels in October. The secondary question asks how often parcels departed late within each team’s own workload. One team can lead on volume of misses while a smaller team has a higher risk per parcel. Keep both questions visible when you present the result.
Pivot data analysis in Python fits because every parcel already belongs to a depot and a shift. Put depots down the rows and shifts across the columns. A cell then has a precise meaning, such as all parcels assigned to Mirpur’s evening shift. A plain pivot expects a single value for each pair. A pivot table can combine many parcel records that share that pair.
Derive a true-or-false late flag by comparing departure with cutoff. Count parcels in each cell, add its true flags, and divide that sum by the cell’s parcel count. Retain both counts beside the percentage so someone reading the table can see the size of the group.
Finally, check that the six cells account for the full log. A forecast would answer a future staffing question and would need additional evidence. Here the promised deliverable is a defensible choice of where to observe first.
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.
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
Key takeaway: Read a cell by naming its row, column and measure.
METHOD CHOICE
Match the tool to the question
A supervisor tracing one parcel needs the original record. A supervisor comparing all morning and evening teams needs an overview with consistent labels. Choose a pivot table when several records share a pair of labels and a summary such as a count has a clear business meaning. Use a simple pivot when each pair already has one value. Keep the original log available so you can investigate a surprising cell.
One parcel → lookup
Many parcels per pair → pivot table
Key takeaway: Decide what a single output cell should mean before reshaping.
CELL MEMBERSHIP
Follow three parcels into one cell
In the small example at the right, all three parcels belong to the same depot and shift. Two depart after their cutoff and one leaves on time. Count the three parcel IDs to get workload. Add the late flags to get two misses. Moving a parcel to a different shift changes both cells involved. This is why the assigned shift in the log matters more than guessing the shift from a late departure.
True + False + True = 2 misses
Key takeaway: The keys select the records. The aggregation combines them.
WORKFLOW
Build the two counts before the rate
Start with a unique parcel ID and usable timestamps. Compare each departure with its own cutoff to create a late flag. Pivot the same records twice: once for workload and once for late parcels. Divide the second table by the first after checking the labels. Keep these steps separate so a supervisor can inspect the evidence behind any percentage, even when the headline report rounds it to two decimal places.
# Compare departure with the cutoff to identify a late parcel.
departed_at > cutoff_at
Key takeaway: Keep both the numerator and denominator available for review.
PIVOT MATH
Weight each parcel equally
Let L be the number of late parcels in a cell and N its workload. Multiply L divided by N by one hundred to get a percentage. Across several cells, add the late parcels and divide by the combined workload. In the teaching example, the smaller team misses half its parcels while the larger team misses none. Their combined rate is ten percent because the ten parcels each get one vote.
Cell rate = 100 × L / N
Combined rate = 100 × ΣL / ΣN
Key takeaway: Combine the underlying counts before calculating an overall rate.
PANDAS SYNTAX
Assign a job to each argument
Start from log, the DataFrame that holds the dispatch rows. Call pivot_table and set index to the label you want down the left. Set columns to the label you want across the top. The values argument picks the field to summarize and aggfunc tells pandas which calculation to apply. Counting parcel IDs works here because earlier checks confirm that each parcel has one record and a present ID.
# Start building the parcel volume table.
volume = log.pivot_table(
# Group rows by depot and create one column per shift.
index='depot', columns='shift',
# Count the parcel IDs in each depot and shift.
values='parcel_id', aggfunc='count'
# Finish the pivot table call and assign the result to volume.
)
Key takeaway: Specify the aggregation explicitly. The default mean answers a different question.
CALCULATIONS
Divide matching cells by label
The misses table stores how many parcels were late. The volume table stores how many were dispatched. The first instruction divides one table by the other. Pandas matches the depot names and shift labels, so each fraction uses the workload of the same team. The next instruction multiplies the fractions by one hundred. If a depot and shift were absent, keep its rate missing until you can explain the gap.
# Divide each late count by the corresponding parcel volume.
fraction = misses.div(volume)
# Convert each fraction to a percentage.
rate = fraction.mul(100)
Key takeaway: A missing group and an observed group with zero misses mean different things.
VALIDATION
Reconcile the report with the log
Before ranking teams, ask whether the grid contains all the parcels. Add each column and then add the column totals. Compare that number with the count of original records. Repeat the check for misses against the original late flags. These checks catch lost rows and many incorrect aggregations. They will not expose a correctly counted parcel assigned to the wrong depot, so still check examples against the source.
# Check the total parcel count against the source row count.
volume.sum().sum() == len(log)
# Check the total late count against the original late flags.
misses.sum().sum() == log['late'].sum()
Key takeaway: Reconcile both totals, then inspect a cell against source records.
INTERPRETATION
Change the measure, change the leader
Look at the two evening teams that lead this report. Dhanmondi has more late parcels, so it accounts for a larger part of the observed workload problem. Mirpur handles fewer evening parcels and misses a larger share of them. Ranking only by percentage would send the observer to a different desk. Neither comparison measures the length of each delay. For a question about minutes lost, calculate elapsed time as a separate measure.
Count asks “how many?”
Rate asks “out of how many?”
Key takeaway: Use the measure that matches the decision, and show its denominator.
BUSINESS DECISION
Choose the first handover to observe
The director asked for the team with the greatest number of missed departures. Begin with Dhanmondi’s evening handover and check the recorded sequence of packing, loading and departure. Ask Mirpur’s evening supervisor to review the frequent misses within that smaller workload. Take these findings into the next operations meeting with the month and parcel counts attached. October’s pattern identifies where to look first. It does not identify the cause of a delay.
Review one shift → record the cause → compare next period
Key takeaway: Make the first action specific enough for someone to carry out next week.
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.
01import as pd
# Read the CSV and parse both timestamps so they can be compared.
# Import pandas to analyze the parcel dispatch log.
import pandas as pd
# Read the CSV and parse both timestamps so they can be compared.
log = pd.read_csv("dispatch_log.csv", parse_dates=["cutoff_at", "departed_at"])
# Check that each parcel ID appears only once.
assert log["parcel_id"].is_unique, "Repeated parcel ID"
# Require a value in every dispatch field before calculating rates.
assert log.notna().all().all(), "Missing dispatch field"
# Check that all depot names belong to the three expected locations.
assert log["depot"].isin(["Dhanmondi", "Mirpur", "Uttara"]).all(), "Unknown depot"
# Check that every shift is labeled AM or PM.
assert log["shift"].isin(["AM", "PM"]).all(), "Unknown shift"
# Flag a parcel as late when it departs after its cutoff time.
log["late"] = log["departed_at"].gt(log["cutoff_at"])
# Count parcels for each depot and shift to get the total volume.
volume = log.pivot_table(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", aggfunc="sum")
# Check that the volume table accounts for every parcel in the log.
assert volume.sum().sum() == len(log), "Volume does not reconcile"
# Check that the late-count table accounts for every flagged parcel.
assert misses.sum().sum() == log["late"].sum(), "Late count does not reconcile"
# Divide late counts by matching parcel totals and convert to percentages.
rate = misses.div(volume).mul(100)
# Calculate the percentage of all parcels that departed late.
network_rate = 100 * log["late"].mean()
# Stack the late counts into a series indexed by depot and shift.
counts = misses.stack()
# Stack the late percentages into a series indexed by depot and shift.
rates = rate.stack()
# Find the depot and shift with the largest late count, taking the first tie.
most_late = counts.idxmax()
# Find the depot and shift with the highest late percentage, taking the first tie.
highest_rate = rates.idxmax()
# Calculate the selected shift’s share of all late parcels across the network.
share = 100 * counts.loc[most_late] / counts.sum()
# Display the parcel volume table with depots as rows and shifts as columns.
print("PARCELS", volume.to_string(), sep="\n")
# Display the late parcel counts for each depot and shift.
print("LATE PARCELS", misses.to_string(), sep="\n")
# Display the late percentages rounded to two decimal places.
print("LATE RATE (%)", rate.round(2).to_string(), sep="\n")
# Print the network-wide late percentage to two decimal places.
print(f"Network late rate: {network_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]} | {counts.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]} | {rates.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: {share:.2f}%")
Complete code walkthrough
LINE 01
Give pandas a short name
# Import pandas to analyze the parcel dispatch log.
import pandas as pd
The import statement makes a library available in this Python session. Pandas provides the DataFrame, a table with named columns and an index for its rows. The words as pd give the library a short local name. No data has been loaded yet.
When the next instruction starts with pd, Python looks for a function in this library. Using the same alias throughout the script makes it easier to distinguish a library function from an operation on an existing table.
LINE 02
Read the dispatch log and parse its clocks
# Read the CSV and parse both timestamps so they can be compared.
log = pd.read_csv("dispatch_log.csv", parse_dates=["cutoff_at", "departed_at"])
The reader opens dispatch_log.csv and returns a DataFrame named log. The first record supplies column headings. Each following record describes a parcel. The browser places the downloaded data in Python’s working directory before this instruction runs.
The parse_dates argument identifies the two columns that hold local timestamps. That makes chronological comparisons meaningful. Treating dates as ordinary text can give surprising results when formats vary. Both columns in this file use the same date format and local clock.
LINE 03
Check the unit of observation
# Check that each parcel ID appears only once.
assert log["parcel_id"].is_unique, "Repeated parcel ID"
Selecting parcel_id produces a Series, a single labeled column. Its uniqueness property returns one Boolean value for the entire column. An assert statement stops the script if that value is false and displays the supplied message.
This check protects the meaning of workload. If a parcel had separate packing and departure scans on different rows, counting rows would overstate the workload. Inspect repeated IDs before deciding which event should represent a parcel.
LINE 04
Catch incomplete dispatch records
# Require a value in every dispatch field before calculating rates.
assert log.notna().all().all(), "Missing dispatch field"
The first method builds a table of true and false values with the same shape as the source. A true value means the original field was present. The first all checks down each column and the second checks the resulting column summaries.
This prevents a missing depot from disappearing during grouping and a missing timestamp from silently affecting a late flag. A missing value check alone cannot tell whether a present value is sensible, which is why the next lines inspect the labels.
LINE 05
Validate the row labels
# Check that all depot names belong to the three expected locations.
assert log["depot"].isin(["Dhanmondi", "Mirpur", "Uttara"]).all(), "Unknown depot"
The list contains the three depots covered by the October brief. The membership check returns one Boolean per parcel. The final all requires every entry to match a listed spelling before the analysis proceeds.
A trailing space on a depot name could otherwise create a fourth row. On a fresh extract, investigate an unfamiliar depot with the dispatch team. It may be a genuine new location that needs to be added to the reporting scope.
LINE 06
Validate the column labels
# Check that every shift is labeled AM or PM.
assert log["shift"].isin(["AM", "PM"]).all(), "Unknown shift"
The second membership check looks at the shift assigned to the parcel. Only AM and PM belong to this report. Checking the labels before the pivot keeps a spelling error from appearing as an unexpected third column.
Use the recorded assignment consistently. A late departure can cross a handover boundary. Reassigning it based on the actual clock time would move a miss away from the team whose cutoff you want to examine.
LINE 07
Turn the cutoff promise into a flag
# Flag a parcel as late when it departs after its cutoff time.
log["late"] = log["departed_at"].gt(log["cutoff_at"])
The comparison operates row by row. It returns true when the recorded departure is later than that parcel’s cutoff. A departure at exactly the promised minute yields false. Assignment with square brackets adds the resulting Boolean Series as a column named late.
A parcel that leaves one minute late contributes the same flag as a parcel that leaves forty minutes late. That matches the director’s measure of missed parcels. Keep the original timestamps for a later question about the duration of delays.
LINE 08
Count the workload in each cell
# Count parcels for each depot and shift to get the total volume.
volume = log.pivot_table(index="depot", columns="shift", values="parcel_id", aggfunc="count")
Pandas groups records by the pair formed by depot and shift. The index argument lays out depot labels vertically and columns lays out shifts horizontally. The values argument selects parcel IDs. The count aggregation counts the present IDs within each pair.
The returned DataFrame, volume, has three rows and two columns here. One cell contains all 60 Dhanmondi PM parcels. Counting IDs is meaningful because the earlier checks established that IDs are present and unique. A simple pivot would encounter repeated pairs.
LINE 09
Count late parcels without dropping on-time work
# Sum the late flags to count late parcels for each depot and shift.
misses = log.pivot_table(index="depot", columns="shift", values="late", aggfunc="sum")
The second table uses the same row and column keys, but its values come from the Boolean late field. Summing Booleans adds one for every true value and zero for every false value. The result stores a count of misses for each depot and shift.
Counting this field instead would include false flags because they are present values. A cell could then look as though every single parcel had left late. Dhanmondi PM should count 18 late flags among its 60 parcels.
LINE 10
Reconcile total workload
# Check that the volume table accounts for every parcel in the log.
assert volume.sum().sum() == len(log), "Volume does not reconcile"
The first sum adds down the depot rows to give one total for each shift. The second sum adds those shift totals into one number. Compare that number with the number of source records using a double equals sign.
This assertion ties the displayed workload back to all 300 parcels. A passing total does not verify the depot of each parcel. Two incorrect assignments could cancel, so keep the earlier label checks and inspect individual cells as well.
LINE 11
Reconcile total misses
# Check that the late-count table accounts for every flagged parcel.
assert misses.sum().sum() == log["late"].sum(), "Late count does not reconcile"
The left side adds all six counts in the misses table. The right side goes back to the original log and adds the late flags directly. Both should give 57 for this file. The comparison produces one Boolean for the assertion.
This check is separate from the workload check. A report could include every parcel while treating an on-time departure as late. Reconciliation checks consistency between representations. The strict cutoff comparison still determines whether the business definition is correct.
LINE 12
Calculate six rates with aligned labels
# Divide late counts by matching parcel totals and convert to percentages.
rate = misses.div(volume).mul(100)
The division pairs each miss count with its corresponding workload by matching row and column labels. Multiplication by one hundred converts each fraction to a percentage. The resulting DataFrame, rate, keeps the same depot and shift labels as both inputs.
For Mirpur PM the calculation is 15 divided by 42 times 100, about 35.71%. A missing group would have no observed denominator. Preserve a missing rate for that case so a reader cannot confuse absent evidence with zero late parcels.
LINE 13
Use every parcel to estimate the network rate
# Calculate the percentage of all parcels that departed late.
network_rate = 100 * log["late"].mean()
For a Boolean Series, the mean is the sum of its true indicators divided by the number of observations. Each of the 300 parcels contributes exactly once. Multiplication by one hundred gives the network late rate, 19.00%.
A simple mean of the six cell percentages gives a small team the same influence as a busy one. Calculating from the complete log automatically weights teams by the number of parcels they handled.
LINE 14
Give each count a two-part address
# Stack the late counts into a series indexed by depot and shift.
counts = misses.stack()
Stacking moves the shift labels below the depot labels in a two-level row index. The result is a Series named counts with one number per observed depot and shift pair. The values themselves stay the same.
This shape makes it easy to compare all six cells with one operation. Looking for the maximum directly on the wide DataFrame would normally produce a separate answer for each column, leaving the director without a single team.
LINE 15
Make the rates searchable by team
# Stack the late percentages into a series indexed by depot and shift.
rates = rate.stack()
Apply the same reshape to the rate table. Its values are percentages and each index entry is a depot and shift pair. Use the full stored precision at this stage. Rounding can make two genuinely different rates appear tied.
Because both Series use the same team labels, you can retrieve the count or rate for a selected team without relying on its position in a printed table.
LINE 16
Find the first team to observe
# Find the depot and shift with the largest late count, taking the first tie.
most_late = counts.idxmax()
This method locates the maximum miss count and returns its index label. In this Series the label is a pair, Dhanmondi and PM. The variable most_late therefore stores an address you can reuse, rather than the number 18.
The largest miss count is unique in October. If two teams tied in a later month, this method would return the first maximum. Report all tied cells or agree on a secondary decision rule before scheduling the observer.
LINE 17
Find where misses were most frequent
# Find the depot and shift with the highest late percentage, taking the first tie.
highest_rate = rates.idxmax()
The same search on the percentage Series returns Mirpur and PM. It answers a different question because every late count has now been divided by its own workload. The winning cell has 15 misses among 42 parcels.
Saving the label separately lets the final report show both conclusions. The team with the poorest observed reliability is worth discussing even when the director’s first review is allocated by absolute miss count.
LINE 18
Measure the share of network misses
# Calculate the selected shift’s share of all late parcels across the network.
share = 100 * counts.loc[most_late] / counts.sum()
A label-based lookup retrieves the miss count for the selected team. The denominator sums all entries in counts, which represents every late parcel in the network. With this file the fraction is 18 divided by 57. Multiplying by one hundred gives 31.58% after rounding.
The denominator here is different from Dhanmondi PM’s 60 dispatched parcels. Share of network misses helps explain review priority. The team’s own late rate describes the reliability of that shift.
LINE 19
Display the workload table
# Display the parcel volume table with depots as rows and shifts as columns.
print("PARCELS", volume.to_string(), sep="\n")
The print function writes a heading and a text representation of the workload table. Its separator is a newline, so the table starts below the heading. The conversion to a string preserves depot and shift names in the console.
Read across a depot to compare morning and evening workload. Managers will need these denominators next to the miss counts. Reporting only a percentage can hide how small or large a team’s workload was.
LINE 20
Display missed departures
# Display the late parcel counts for each depot and shift.
print("LATE PARCELS", misses.to_string(), sep="\n")
This line prints the misses table in the same orientation as the workload table. Keeping the depot and shift labels visible helps the reader check one team across both tables without learning a new layout.
Look at Dhanmondi’s PM column. There are 18 missed parcels there. That is enough to identify a candidate under the director’s count rule, but you still need the corresponding workload to discuss the team’s reliability.
LINE 21
Show percentages at readable precision
# Display the late percentages rounded to two decimal places.
print("LATE RATE (%)", rate.round(2).to_string(), sep="\n")
Rounding returns a version of the rate table with values rounded to two decimal places. The original rate variable keeps its full precision because the rounded copy is passed directly into the display operation. The heading includes a percent sign to identify the units.
For Mirpur PM the display reads 35.71. Read this as 35.71 percent of that team’s parcels in October. It is a descriptive result for the observed period.
LINE 22
Print the overall baseline
# Print the network-wide late percentage to two decimal places.
print(f"Network late rate: {network_rate:.2f}%")
The letter f introduces a formatted string. Python evaluates the expression inside braces and places its value in the sentence. The format .2f requests two digits after the decimal point, giving 19.00%.
This baseline represents the full October workload. It helps put each team’s rate in context. It is not a service target set by management, so avoid using it as a contractual benchmark in the report.
LINE 23
Name the highest-count team and its workload of misses
# 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]} | {counts.loc[most_late]} parcels")
The two positions of most_late hold the depot and shift labels. Inserting both gives the director a specific place and time. The label-based lookup retrieves the miss count, so the sentence can report the reason behind the selection.
The resulting report identifies Dhanmondi PM and 18 parcels. Keeping the lookup tied to the computed winner makes the sentence update when a new period produces a different ranking.
LINE 24
Report the highest-rate team
# Report the depot and shift with the highest late percentage and its rate.
print(f"Highest rate: {highest_rate[0]} {highest_rate[1]} | {rates.loc[highest_rate]:.2f}%")
The tuple highest_rate supplies the depot and shift for the highest observed percentage. Retrieve the actual percentage from rates using that same label. Formatting changes only the printed value and keeps the internal rate available for further comparison.
Mirpur PM appears here even though it did not lead the count table. The figure describes a team’s recorded departures. Predicting whether a future parcel will be late would require more information.
LINE 25
Explain the scale of the review
# 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: {share:.2f}%")
The final line formats the share of network misses as a percentage. Of all missed October cutoffs, 31.58% belonged to the team selected for the first observation. The value is already on a zero-to-one-hundred scale, so there is no second multiplication.
Use this figure to explain why the handover deserves attention. Observing those parcels can reveal process details. The share alone cannot tell how many misses a staffing change could prevent.
Verified reference output
(300, 6)
REGIONS
revenue profit orders margin_pct
region
North 39590 10422 100 26.32
South 36515 11227 125 30.75
West 21380 6012 75 28.12
CATEGORIES
revenue profit orders units margin_pct
category
Home 30105 12329 106 404 40.95
Electronics 56215 10039 91 312 17.86
Office 11165 5293 103 367 47.41
TOP SEGMENTS
region category revenue profit orders
South Home 14405 5869 50
North Electronics 26355 4747 39
North Home 9480 3936 31
300Parcels reconciled
57Missed cutoffs
19.00%Network late rate
Understanding the results
The October grid accounts for all 300 parcels and all 57 missed cutoffs. The network late rate is 19.00%. This is the fraction of individual parcels that left late across all six teams. Workloads range from 30 to 70 parcels, so giving every cell the same weight would change the question.
Dhanmondi PM recorded 18 misses in 60 parcels, or 30.00%. Mirpur PM recorded 15 misses in 42 parcels, or 35.71%. The first cell has three more misses; the second has a higher frequency within its own workload. Selecting a review by count and selecting one by rate produce different choices here.
Every evening shift had a higher observed late rate than its depot’s morning shift. The log covers one month and contains no packing, loading or staffing events. Further observation is needed to explain that pattern.
BUSINESS RECOMMENDATION
18 late parcels
Dhanmondi · PM handover
31.58% of the network’s October misses
Send the observer to Dhanmondi’s evening handover first. Its 18 late parcels account for 31.58% of all 57 missed cutoffs in October. Follow parcels from packing to loading, compare physical departures with scan times, and ask the shift lead to record where waiting begins. The count gives the director a reason to spend the single observation slot there.
Flag Mirpur’s evening shift for a separate discussion. Fifteen of its 42 parcels departed late, which is the highest observed rate. Before moving staff, compare the next period’s parcel volumes, late counts and rates for both teams. Ask whether truck schedules or the timing of incoming work changed. Those details can distinguish a handover issue from delays that began earlier.
08
End of the lesson
Reflect on your learning experience.
How was your learning experience?
Select a rating
Explore more lessons
Continue building practical skills with other interactive labs.
APPLIED DATA ANALYTICS
Data cleaning in python — 10 Essential Steps to Better Data
Practice Data cleaning in python on warehouse receipts. Inspect data types, fix inconsistent values, remove duplicates, and verify dock totals in a hands-on lab.
Data Joining in python — 3 Essential Checks for Better Parcel Pricing
Data Joining in python with pandas. Stack parcel manifests, merge zone tariffs, verify every shipment and reconcile delivery charges in an interactive coding lab.
Group by data analysis in Python: 10 Powerful Steps to Success
Learn Group by data analysis in Python through 10 visual lessons, a real-world retail project, pandas exercises, revenue summaries and profit analysis.
Missing value in Python — 10 Essential Steps to Better Data
Learn to detect a Missing value in Python and use SimpleImputer to repair a delivery dataset. Explore 10 visual slides and run a hands-on Python exercise.