Module 2 · Section 6 of 12
Lesson 2.5 - Sorting & Ranking
Target: ~7 min read - 15 min hands-on
Overview
.sort_values() orders a DataFrame by one or more columns - ascending or descending.
This lesson uses it to rank sites by total energy and rank individual days by
consumption, a pattern you'll reuse for ranking assets by cost, runtime, or load.
Why This Matters (Engineering Context)
Ranking sites or days by extremity is usually the first step in deciding which records deserve closer attention - the top-10 consumption days feed directly into a demand-charge or peak-shaving study, for instance.
Code-Along
# --- Rank sites by total energy over the period ---
# groupby("site") splits the data into one group per site
# ["energy_kwh"] selects just that column from each group
# .sum() adds up all the energy_kwh values within each site's group
# .reset_index() turns the grouped result back into a regular DataFrame
# (otherwise "site" would be stuck as the index instead of a normal column)
site_totals = energy_df.groupby("site")["energy_kwh"].sum().reset_index()
# Sort sites from highest total energy to lowest (ascending=False = descending order)
site_totals_sorted = site_totals.sort_values("energy_kwh", ascending=False)
print("Sites ranked by total energy (2021-2023):")
print(site_totals_sorted)
# --- Top 5 single-day consumption readings across the whole dataset ---
# Sort ALL rows (every site, every day) by energy_kwh descending,
# then keep just the top 5 highest individual daily readings
top5_days = energy_df.sort_values("energy_kwh", ascending=False).head(5)
# Show only the relevant columns for readability
top5_days[["site", "date", "energy_kwh"]]
Run it: Charlie DC (Data Center, highest base load) should sit at the top of the
site ranking; top5_days shows the five single heaviest-consumption days by any site.
Practice Exercises
- Sort
energy_dfbydateascending, then byenergy_kwhdescending within each date (sort_values(["date", "energy_kwh"], ascending=[True, False])) - what does this ordering accomplish? - Rank sites by average (not total) daily energy, using
.groupby("site")["energy_kwh"].mean(). - Find the single hottest day (
ambient_c) in the dataset and print its site and date.
# Try the practice exercises here
Knowledge Check
- What method sorts a DataFrame by column values?
- How do you sort in descending order?
- Why might ranking by total energy vs. average energy give different site orderings?
Answer key
.sort_values()- Pass
ascending=False - Total is affected by how many days a site reported data; average normalizes for that
16 / 63 sections · Course home · Join the coaching cohort