Data sorting & filtering in python — 5 Essential Filters for Better Dispatch Decisions
Use Data sorting & filtering in python to choose three repair visits from a busy service queue. Apply five eligibility tests, resolve priority ties and give dispatch a ranked work order.
At Alder Field Service, a fictional repair company, the morning dispatch team has three visits to book for its pump crew. The service desk exports one list for the entire network. Closed jobs sit beside open requests, and a recently edited record can appear at the top even when another customer has waited longer. Yesterday two coordinators picked different jobs from the same file. Today the supervisor wants a list either coordinator can reproduce before calling the customers.
The crew serves North and East. It takes open pump jobs that have waited at least three days and have an estimated visit of one to two hours, including both limits. The asset description identifies pump work, but technicians use different capitalization and occasionally leave the field empty. The export also includes a unique job ID, current status, district and waiting time measured at the morning snapshot.
Which three jobs should the desk call first? Give the oldest eligible jobs priority. If two have waited equally long, choose the shorter visit first. If both values match, use the smaller job ID. Keep the other eligible jobs in order so the desk can fill a cancelled visit without starting again.
02
Your role
▥
YOUR ASSIGNMENT
Dispatch Data Analyst
You are the dispatch data analyst working alongside the morning coordinator. Your first responsibility is to turn the crew’s booking rules into tests that another analyst could repeat. Pay attention to the limits of the visit window, the meaning of a blank equipment description and the difference between a job’s age and its position in the export.
Deliver a ranked three-job handoff with the identifiers, waiting times and estimated hours the coordinator needs for the calls. Keep a reserve list and reconcile its size with the eligible pool. Be ready to explain why two jobs of the same age can receive different priorities and what the coordinator should recheck before confirming a visit.
03
Identify the problem
Which jobs can this crew take, and how should dispatch choose the first three?
Identify the business outcome, suitable technique and why you would choose it.
Expert Problem Formulation
The desk needs two decisions for each repair request. First, can this particular crew take it? Second, if it qualifies, where does it belong in the queue? A long wait matters only after a job passes the crew’s rules. An old closed request could otherwise take a slot away from an open one.
Use one yes-or-no test for each eligibility rule. Read status and district as labels, age and hours as numbers, and the asset description as text. Combine the tests so a row survives only when every requirement holds. A missing description leaves the desk without evidence of pump work, so the job stays outside this crew’s shortlist.
Sort the survivors by decreasing age, then by increasing duration and ID. Apply the three-slot limit after that sort. Summarizing by district could describe workload, but it would discard the row-level detail the coordinator needs. Predicting a priority score would introduce assumptions when the supervisor has already specified the decision rule.
Return the ranked IDs with their age and duration, along with the remaining ordered candidates. The result explains the selection at the time of export. Before calling a customer, confirm the job is still open.
04
Investigate
Ask the right questions before developing your solution.
Q01What makes a job eligible for one of the three slots?
A slot belongs to one identifiable repair job. Start with jobs marked Open and require a wait of at least three days. The district must be North or East, the duration must fall between one and two hours including the endpoints, and the asset description must contain the word fragment pump in any capitalization. These conditions answer whether the crew can take a job. They do not decide which qualifying job goes first. For example, a five-day pump job in West stays outside this list even when the crew has an unused slot.
Q02Which fields could change a dispatch decision?
Read the six columns as a snapshot. The job ID identifies a request, status indicates whether it is still available, and district identifies the service area. Waiting days and estimated hours use different units, so comparing the wrong column can produce a plausible but misleading list. The asset description is free text. A technician can enter PUMP motor or Pump seal, and some descriptions are blank. Treat a blank as insufficient evidence. Check the IDs before ranking because a repeated job could otherwise occupy two positions in the handoff.
Q03How do filtering and sorting work together?
A filter tests each row and keeps the ones that pass. Sorting changes the sequence of those survivors while carrying every field along with its job ID. Start with the full snapshot and combine all five eligibility conditions. Then sort the eligible table using the supervisor’s rules. For two jobs waiting fourteen days, the shorter visit wins. For equal waits and equal visits, compare job IDs. Take the first three only after sorting. If you take three rows from the export first, a better candidate farther down the file never gets considered.
Q04What would convince us that the queue is correct?
Check examples on both sides of each boundary. A job waiting exactly three days should pass the age test. A one-hour or two-hour visit should pass the duration test, while a half-hour visit should fail it. Look at adjacent rows in the ranked table. Age should never increase as you read downward, and durations should increase or stay equal within each age group. Finally, add the selected and reserve counts and compare the sum with the eligible count. This last check catches a skipped position even when every visible job looks reasonable.
Q05How should the coordinator use the reserve list?
Use the three selected rows as a call order. Before booking, verify the customer is available, the request is still open and the crew can reach the site. If a selected visit falls through, take the first still-eligible job from the reserve list. Keep the reason for the change with the handoff so a colleague can reconstruct it. The dataset has no travel times, appointment windows or live stock information. The ranking supports a fair starting order under the agreed rule. The coordinator still owns the final appointment decision.
job_id identifies a repair request. status and district describe availability and coverage. wait_days is the age at export, hours is the estimated visit length, and asset is the technician’s equipment description.
06
Topic Lesson — Data sorting & filtering in python
Explore the topic through interactive visual learning.
TOPIC LESSON
01 / 10
FOUNDATIONS
Choose rows, then choose their order
Think of the service export as a stack of job cards. Filtering removes cards that this crew cannot take. Sorting arranges the remaining cards so the first one has a clear claim on the next slot. Both operations work on whole rows, which keeps each job ID attached to its own age and duration. The result is a smaller table in a meaningful order.
Use these operations when the decision rules are known and the data already records what the rules need. If a planner asks which jobs qualify today, test the current rows. If they ask which open job is oldest, order those rows. Predicting how long a future repair will actually take would require historical outcomes and a different analysis. The estimated hours here are an input supplied by dispatch.
Input: current snapshot and a booking policy.
Key takeaway · Match the operation to the decision the desk needs.
BOOLEAN MASKS
Give every source row a yes-or-no answer
An exact match compares a label with one permitted value. A threshold compares a number with a limit. Each comparison produces a Boolean mask, a column of True and False values indexed like the source. Combine the masks for the same job. An open job at the three-day boundary passes both tests. A closed job can pass the age test and still fail the combined rule.
Status equals Open AND waiting days ≥ 3.
Key takeaway · A passing value in one column cannot rescue a failing row.
WORKFLOW
Use five filters before ranking
Start with exact status and a minimum age. Next test district membership, then require an estimated duration inside the booking window. Finally search the asset text for pump, ignoring case. A missing description fails that last test. Only after all five decisions agree do you need to rank the surviving jobs. Applying the three-slot limit to the unfiltered export would give input order more influence than the policy allows.
Snapshot → eligible pool → ranked pool → dispatch.
Key takeaway · Select eligible jobs before limiting the queue.
LOGIC LAB
Test the endpoints explicitly
The booking window is a closed interval. The lower bound and upper bound both count. One way to test a value is to ask two questions: is it at least one, and is it at most two? Only a pair of true answers passes. Membership uses a different rule. North or East is enough because the job belongs to just one district. Inside the full eligibility rule, these two tests must both pass.
1 ≤ estimated hours ≤ 2
Key takeaway · Use AND across required conditions and OR within the district list.
IMPLEMENTATION
Build a range mask and a text mask
Read the duration comparison from left to right. Start with the hours column, supply the bounds and tell pandas to include both ends. Then search the descriptions using the string accessor. A literal, case-insensitive search covers both pump spellings in the file. The missing-value option gives an empty description a definite False. Both statements create masks and leave the source table available for the other tests.
# Check the estimated duration against the booking window.
fits_slot = jobs["hours"].between(1, 2, inclusive="both")
# Find pump descriptions regardless of capitalization.
pump = jobs["asset"].str.contains("pump", case=False, regex=False, na=False)
Key takeaway · Explicit text and boundary rules make edge cases reproducible.
IMPLEMENTATION
Rank whole jobs and take three
The eligible table contains the jobs this crew can take. Supply the three priority columns in order, with one direction for each. Read False as descending for waiting time and True as ascending for hours and ID. The result is a new ordered table. Taking its first three rows implements capacity. Sorting each column independently would break the link between a request and its service information.
# Rank by oldest wait, shortest visit and then job ID.
ranked = pool.sort_values(["wait_days", "hours", "job_id"], ascending=[False, True, True])
# Select the first three ranked jobs.
dispatch = ranked.head(3)
Key takeaway · A unique final key makes the handoff repeatable.
OUTPUT CHECK
Reconcile the dispatch split
The snapshot contains 300 jobs. The five checks together admit 26. Dispatch takes three, leaving 23 qualified reserves. The remaining 274 failed at least one condition. A job can fail several rules, so adding individual failure counts could count the same job twice. Check the final mask and reconcile the allocation instead. A matching count is only the first check. Also verify the returned IDs and their order.
3 selected + 23 reserve = 26 eligible.
Key takeaway · Reconcile counts and inspect identities and ordering.
INTERPRETATION
Explain why a tie changes the call order
Two selected jobs have waited fourteen days. Under the agreed priority rule they both come before the thirteen-day job. Between the two older requests, estimated duration decides the order. The one-hour visit precedes the one-and-a-half-hour visit. This is a practical reason to keep both sort directions visible in the handoff. Sorting only by age makes the first call depend on how the export happened to arrive.
Age first. Duration breaks the fourteen-day tie.
Key takeaway · Explain a ranking by the first key on which the jobs differ.
DECISION
Turn the ranked table into calls
Offer visits to the three selected jobs in ranked order. The desk should verify availability before promising an appointment because the file records a single moment in time. A declined visit opens one place. Move to the first still-eligible reserve instead of rebuilding the list by hand. If the crew’s district coverage or slot lengths change, recalculate from the full snapshot using the new rules.
First call: J0253, a fourteen-day wait and a one-hour estimate.
Key takeaway · The queue sets call priority. Confirmation turns a candidate into a booking.
1 / 10 slides explored
07
Build the solution
Complete the missing Python operations and run your analysis.
Build the morning dispatch queue
Fill each blank with one Python identifier. Use the hint beside a line when you need a clue. The dataset loads automatically when you submit your code.
dispatch_queue.py0 / 18 filled
01# Load the table analysis library.
02import as pd
03# Read the dispatch snapshot from disk.
04jobs = pd.("service_jobs.csv")
05# Verify that each job appears only once.
06assert jobs["job_id"].
07# Check every job has an identifier.
08assert jobs["job_id"].notna().()
09# Identify jobs still open for dispatch.
10open_job = jobs["status"].("Open")
11# Identify jobs waiting at least three days.
12old_enough = jobs["wait_days"].(3)
13# Select districts served by this crew.
14in_area = jobs["district"].(["North", "East"])
15# Check the estimated duration against the booking window.
# Load the table analysis library.
import pandas as pd
# Read the dispatch snapshot from disk.
jobs = pd.read_csv("service_jobs.csv")
# Verify that each job appears only once.
assert jobs["job_id"].is_unique
# Check every job has an identifier.
assert jobs["job_id"].notna().all()
# Identify jobs still open for dispatch.
open_job = jobs["status"].eq("Open")
# Identify jobs waiting at least three days.
old_enough = jobs["wait_days"].ge(3)
# Select districts served by this crew.
in_area = jobs["district"].isin(["North", "East"])
# Check the estimated duration against the booking window.
fits_slot = jobs["hours"].between(1, 2, inclusive="both")
# Find pump descriptions regardless of capitalization.
pump = jobs["asset"].str.contains("pump", case=False, regex=False, na=False)
# Require every eligibility condition to pass.
eligible = open_job & old_enough & in_area & fits_slot & pump
# Keep the full records for qualifying jobs.
pool = jobs.loc[eligible]
# Rank by oldest wait, shortest visit and then job ID.
ranked = pool.sort_values(["wait_days", "hours", "job_id"], ascending=[False, True, True])
# Select the first three ranked jobs.
dispatch = ranked.head(3)
# Set aside qualifying jobs below the cutoff.
reserve = ranked.iloc[3:]
# Confirm every qualifying job has a place.
assert len(dispatch) + len(reserve) == len(pool)
# Choose the fields dispatch needs to see.
handoff = dispatch.loc[:, ["job_id", "wait_days", "hours"]]
# Print the source, eligible and reserve counts.
print(f"Snapshot {len(jobs)} | Eligible {len(pool)} | Reserve {len(reserve)}")
# Display the dispatch table without internal row labels.
print(handoff.to_string(index=False))
Complete code walkthrough
STEP 01 · LINE 02
Bring tables into Python
# Load the table analysis library.
import pandas as pd
Python loads a module and binds it to the short name pd. That name is available for the rest of the program, so the next instruction can use its file reader. Importing a library alone neither opens the dispatch file nor changes a job.
The table will have named columns. That matters here because age, hours and district each follow a different business rule.
STEP 02 · LINE 04
Read one row per service job
# Read the dispatch snapshot from disk.
jobs = pd.read_csv("service_jobs.csv")
The reader treats the first line as column names and builds a DataFrame. A row represents a job at the snapshot time. Numeric age and duration can now be compared with thresholds, while district and status remain labels.
Empty asset cells are read as missing. A later text test will give those rows an explicit outcome. Loading a file twice from different snapshots could change the queue.
STEP 03 · LINE 06
Check the unit of analysis
# Verify that each job appears only once.
assert jobs["job_id"].is_unique
A job identifier should refer to exactly one dispatch decision. The assertion stops the analysis if an identifier repeats. Otherwise two rows could consume two slots for the same repair. This property returns one Boolean for the whole column.
Uniqueness alone does not establish that every ID is present. The following check covers that separate requirement.
STEP 04 · LINE 08
Require a usable identifier
# Check every job has an identifier.
assert jobs["job_id"].notna().all()
Checking for missing values produces one Boolean per row. Reducing those answers to a single value lets the assertion test the entire snapshot. An empty identifier would prevent dispatch from locating a selected job.
A passing assertion prints nothing. From this point, a job ID can serve both as a handoff reference and as the final tie breaker.
STEP 05 · LINE 10
Filter 1 · exact match
# Identify jobs still open for dispatch.
open_job = jobs["status"].eq("Open")
The comparison creates a Boolean Series aligned with the original row index. Open receives True and Closed receives False. The variable stores decisions, so the original status column remains available for inspection.
Equality is case sensitive. An unexpected spelling would fail this rule. For a live feed, confirm the allowed labels with the service desk before reusing the filter.
STEP 06 · LINE 12
Filter 2 · minimum age
# Identify jobs waiting at least three days.
old_enough = jobs["wait_days"].ge(3)
Wait time is measured in whole days at the snapshot. A job at three days qualifies, as does one at four. A strict greater-than test would silently drop jobs sitting exactly on the policy boundary.
The result has one Boolean for each original row. Keep its index intact so it can later be combined with the other conditions.
STEP 07 · LINE 14
Filter 3 · membership
# Select districts served by this crew.
in_area = jobs["district"].isin(["North", "East"])
This test asks whether a district belongs to the crew’s service list. North and East are alternatives within one rule. A row cannot have both district labels at once, so demanding both would leave the shortlist empty.
Passing the two labels in a list allows dispatch to update coverage later without rewriting a long chain of comparisons.
STEP 08 · LINE 16
Filter 4 · bounded range
# Check the estimated duration against the booking window.
fits_slot = jobs["hours"].between(1, 2, inclusive="both")
Both endpoints belong to the permitted interval. One hour, one and a half hours and two hours fit the crew’s booking rules. Half an hour is below this team’s minimum booking and three hours exceeds its slot.
A duration describes one job. Adding the durations would answer a different scheduling question and would not identify which individual jobs fit.
The string accessor applies a search to each asset description. Ignoring case includes both Pump seal and PUMP motor. Literal matching treats the search term as ordinary text, and the missing-value setting gives a blank description False.
Substring matching has limits. A future description such as “non-pump assembly” would need a more precise rule or an approved equipment code.
STEP 10 · LINE 20
Combine the five requirements
# Require every eligibility condition to pass.
eligible = open_job & old_enough & in_area & fits_slot & pump
The ampersand combines Boolean values row by row. All five must be True for the final decision to be True. Each mask came from the same table, so its index refers to the same job throughout.
Use a vector operation for a column of decisions. Python’s scalar and operator expects a single truth value and cannot resolve a whole Series this way.
STEP 11 · LINE 22
Extract the eligible rows
# Keep the full records for qualifying jobs.
pool = jobs.loc[eligible]
The selector keeps rows whose mask is True. All six original columns travel together, which prevents an identifier from becoming separated from its age or duration. Rows appear in their original order at this point.
This intermediate table separates admission to the queue from priority within the queue. A qualifying job can still miss today’s three available slots.
STEP 12 · LINE 24
Order by policy
# Rank by oldest wait, shortest visit and then job ID.
ranked = pool.sort_values(["wait_days", "hours", "job_id"], ascending=[False, True, True])
The first key has highest priority. False puts the longest wait first. When ages match, True puts the shorter visit first. Only when both age and duration match does the ID determine the order.
Fixed-width job identifiers sort consistently as text. Because IDs are unique, even fully tied age and duration groups have a reproducible order across different input row arrangements.
STEP 13 · LINE 26
Allocate the available slots
# Select the first three ranked jobs.
dispatch = ranked.head(3)
Taking the first three rows after sorting implements the crew’s capacity. Calling this method on the source file would choose by export order. Calling it before filtering could allocate slots to closed jobs.
If fewer than three jobs qualify, pandas returns only the available rows. Dispatch can therefore use this step on quieter shifts too.
STEP 14 · LINE 28
Preserve the waiting list
# Set aside qualifying jobs below the cutoff.
reserve = ranked.iloc[3:]
Positions start at zero. The fourth ranked job therefore occupies position three, and slicing from that position through the end returns the reserve list. Original source index labels may be scattered after sorting.
A position-based slice follows the current priority order. The reserve list lets a coordinator find a replacement if a selected visit cannot go ahead.
STEP 15 · LINE 30
Reconcile the allocation
# Confirm every qualifying job has a place.
assert len(dispatch) + len(reserve) == len(pool)
Adding the selected and reserve counts should recover the size of the eligible table. The assertion catches accidental gaps in the position slices. If no jobs qualify, all three counts are zero and the check still holds.
This verifies the size of the split. Eligibility and ranking need their own checks because an equally large but incorrectly formed pool could still pass.
STEP 16 · LINE 32
Prepare a compact handoff
# Choose the fields dispatch needs to see.
handoff = dispatch.loc[:, ["job_id", "wait_days", "hours"]]
The colon selects every row in dispatch. The list after the comma chooses and orders the three columns in the handoff. The result keeps the ranked order, giving the desk an identifier, a waiting time and a visit estimate for each slot.
Column selection changes the width of the table. It does not recalculate or round the booking estimates.
STEP 17 · LINE 34
Report the size of the decision
# Print the source, eligible and reserve counts.
print(f"Snapshot {len(jobs)} | Eligible {len(pool)} | Reserve {len(reserve)}")
The formatted string inserts the three row counts into one line. Reading the counts together helps a coordinator distinguish the full snapshot from the portion this crew can service. A reserve job already satisfies the same five conditions as a selected job.
This line displays information. It does not return a revised queue or make any bookings.
STEP 18 · LINE 36
Print the ranked work order
# Display the dispatch table without internal row labels.
print(handoff.to_string(index=False))
The table is converted to text before printing. Hiding its internal index prevents a CSV row position from looking like a rank or job identifier. Read the output from top to bottom for the intended assignment order.
The hours are estimates from the snapshot. The crew lead still needs to confirm access and equipment before treating a printed line as an appointment.
Of the 300 jobs in the export, 26 meet all five requirements for this crew. The three selected jobs exhaust the morning slots. The remaining 23 can be considered for cancellations under the same policy. The 274 outside this pool may still need attention from other crews.
J0253 and J0147 have both waited 14 days. The shorter estimate puts J0253 first. J0192 follows with a 13-day wait. These are priorities under the dispatch rule. The estimates alone cannot tell the desk when a technician will arrive or whether a customer can accept a visit.
BUSINESS RECOMMENDATION
14 days waiting
Call J0253 first
First priority · one-hour estimated visit
Offer the first slot to J0253. It shares the longest waiting time in the selected group with J0147, and its one-hour visit breaks the tie in its favor. Call J0147 next and J0192 third. Give the crew the job IDs with their estimated hours so the desk and technicians can confirm they are discussing the same appointments.
Keep the 23 qualified reserves in the computed order. If a customer declines or a job has closed, check the next reserve against the current service record before offering the slot. If travel time or parts availability changes what the crew can take, update the booking criteria and rerun the selection before making further calls.
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.
New lessons will appear here when they are published.
Recommended resource
Explore additional learning resources to deepen your understanding.