Weekday mean at 18:00
1,724.05 completed rentals per operating hour
Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within Weekday.
1,554 completed rentals per operating hour at 18:00 was the highest mean across recorded clock hours in SeoulBikeData.csv.
1,724.05 completed rentals per operating hour
Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within Weekday.
1,161.01 completed rentals per operating hour
Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within Weekend.
542 completed rentals per operating hour
Quantile 0.5 of individual operating-hour counts, with linear interpolation.
295 hours
Count of No rows, one per recorded hour.
hourly-profile · n = 8465
Excluded 295 · Functioning Day = No on 295 rows.
hourly-observations · n = 8465
Excluded 295 · Functioning Day = No on 295 rows.
hourly-distribution · n = 8465
Excluded 295 · Functioning Day = No on 295 rows.
| ID | Item | Status | Answer |
|---|---|---|---|
| A01 | Business process and recording stage | resolved | User confirmed completed systemwide rentals per recorded hour. Rental start timing is unverified.Evidence and options
|
| A02 | Decision | resolved | User requested typical demand comparisons for redistribution staffing.Evidence and options
|
| A03 | Observation unit | resolved | One systemwide count per distinct Date and Hour, verified across 365 dates and confirmed by the user.Evidence and options
|
| A04 | Count unit and eligible denominator | resolved | User selected operating hours for demand comparisons and asked to count suspension hours separately.Evidence and options
|
| A05 | Time basis | unresolved | User does not know the time zone. The analysis groups by recorded date and hour labels.Evidence and options
|
| A06 | Exceptions and normal ranges | resolved | User confirmed No marks suspension. The exploratory high-volume flag retains all observations and uses the operating distribution.Evidence and options
|
| A07 | Missing values and zeros | resolved | No blank cells. Every zero in the rental count occurs on a No row. These rows are used for suspension time and are outside the volume analysis.Evidence and options
|
| A08 | Join keys | not_applicable | Single table with no joins.Evidence and options
|
| Metric | Value | Definition | Numerator | Denominator | Condition | Sources |
|---|---|---|---|---|---|---|
| Overall mean at 18:00 | 1,554.02 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within all operating dates. | 548,568 | 353 |
| |
| Weekday mean at 18:00 | 1,724.05 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within Weekday. | 432,737 | 251 |
| |
| Weekend mean at 17:00 | 1,161.01 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Highest mean over the 24 recorded hour labels within Weekend. | 118,423 | 102 |
| |
| Overall operating-hour mean | 729.16 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. All dates in the source. | 6,172,314 | 8,465 |
| |
| Weekday mean at 08:00 | 1,306.02 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Weekday operating rows at Hour = 8. | 327,810 | 251 |
| |
| Weekend mean at 08:00 | 420.79 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Weekend operating rows at Hour = 8. | 42,921 | 102 |
| |
| Spring operating-hour mean | 746.25 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Operating rows labeled Spring. | 1,611,909 | 2,160 |
| |
| Summer operating-hour mean | 1,034.07 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Operating rows labeled Summer. | 2,283,234 | 2,208 |
| |
| Autumn operating-hour mean | 924.11 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Operating rows labeled Autumn. | 1,790,002 | 1,937 |
| |
| Winter operating-hour mean | 225.54 completed rentals per operating hour | Sum of Rented Bike Count divided by the number of operating rows, one per hour. Operating rows labeled Winter. | 487,169 | 2,160 |
| |
| 25th percentile | 214 completed rentals per operating hour | Quantile 0.25 of individual operating-hour counts, with linear interpolation. |
| |||
| Median operating hour | 542 completed rentals per operating hour | Quantile 0.5 of individual operating-hour counts, with linear interpolation. |
| |||
| 75th percentile | 1,084 completed rentals per operating hour | Quantile 0.75 of individual operating-hour counts, with linear interpolation. |
| |||
| 90th percentile | 1,696.6 completed rentals per operating hour | Quantile 0.9 of individual operating-hour counts, with linear interpolation. |
| |||
| Service suspension hours | 295 hours | Count of No rows, one per recorded hour. |
| |||
| Dates affected by suspensions | 13 recorded dates | Count of distinct recorded dates with at least one No hour. |
| |||
| Fully suspended dates | 12 recorded dates | Count of recorded dates with all 24 rows marked No. |
| |||
| Maximum observed hourly count | 3,556 completed rentals | Largest single operating-hour count in the supplied year. |
|
# From eda-work, run with Python 3.10+ and the supplied skill environment.
# python3 -I ../eda-skill/scripts/inspect_data.py ../SeoulBikeData.csv --out inspection.json
# python3 -I analyze.py
# python3 -I ../eda-skill/scripts/plots.py --spec plot-spec.json --outdir delivery/figures > plot-results.json
# python3 -I prepare_report.py
# python3 -I ../eda-skill/scripts/build_report.py --spec report-spec.json --outdir delivery
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
source = "../SeoulBikeData.csv"
count = "Rented Bike Count"
state = "Functioning Day"
df = pd.read_csv(source, encoding="cp1252", dtype=str, keep_default_na=False)
df.index = pd.Index(range(2, len(df) + 2), name="_source_row")
blank = df.eq("")
assert not blank.any().any()
assert not df.duplicated().any()
date = pd.to_datetime(df["Date"], format="%d/%m/%Y", errors="raise")
hour = pd.to_numeric(df["Hour"], errors="raise")
volume = pd.to_numeric(df[count], errors="raise")
assert (hour % 1 == 0).all() and hour.between(0, 23).all()
assert (volume % 1 == 0).all() and volume.ge(0).all()
times = pd.DatetimeIndex(date + pd.to_timedelta(hour, unit="h"))
assert times.equals(pd.date_range(times.min(), times.max(), freq="h"))
assert set(df[state]) == {"Yes", "No"}
assert volume.eq(0).equals(df[state].eq("No"))
hourly = df.assign(Date=date, Hour=hour, **{count: volume})
hourly["Day type"] = date.dt.day_of_week.ge(5).map({True: "Weekend", False: "Weekday"})
operating = hourly.loc[df[state].eq("Yes")]
suspended = hourly.loc[df[state].eq("No")]
assert len(operating) + len(suspended) == len(df)
assert operating[count].sum() + suspended[count].sum() == volume.sum()
def summarize(rows, by):
return rows.groupby(by)[count].agg(
total="sum", hours="size", mean="mean", median="median",
p90=lambda values: values.quantile(.9),
)
all_hours = summarize(operating, "Hour")
day_hours = summarize(operating, ["Day type", "Hour"])
season = summarize(operating, "Seasons")
print(all_hours.round(2).to_string())
print(day_hours.groupby(level=0)["mean"].nlargest(5).round(2))
print(season.round(2))
print(operating[count].quantile([.25, .5, .75, .9]))
print("Peak observed:", operating.loc[operating[count].idxmax(), ["Date", "Hour", count]].to_dict(), operating[count].idxmax())
print("Suspensions:", suspended["Date"].nunique(), "dates;", suspended.groupby("Date").size().eq(24).sum(), "full dates")
print(hourly.groupby(["Day type", state]).size())
quartiles = operating[count].quantile([.25, .75])
iqr = quartiles.loc[.75] - quartiles.loc[.25]
upper_fence = quartiles.loc[.75] + 1.5 * iqr
print("Upper fence:", upper_fence, "Flagged:", operating[count].gt(upper_fence).sum())
print("Weekday 8 / weekend 8:", day_hours.loc[("Weekday", 8)].to_dict(), day_hours.loc[("Weekend", 8)].to_dict())
out = Path("delivery/figures")
out.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(10, 5), layout="constrained")
ax.set_axisbelow(True)
ax.grid(axis="y", color="#e0e7ef")
ax.plot(all_hours.index, all_hours["mean"], label="All operating hours", color="#34445a", linestyle="--", linewidth=1.8)
for day, color, marker in [("Weekday", "#17699e", "o"), ("Weekend", "#ab4a16", "s")]:
group = day_hours.loc[day]
ax.plot(group.index, group["mean"], label=day, color=color, marker=marker, markersize=3.5, linewidth=2)
peak = group["mean"].idxmax()
ax.scatter(peak, group.loc[peak, "mean"], color=color, marker=marker, s=60, zorder=3)
ax.set(xlim=(-0.25, 23.25), ylim=(0, None), xticks=range(24),
xlabel="Recorded hour (time zone unknown)", ylabel="Mean completed rentals per operating hour",
title="When are completed rentals most concentrated?")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="upper left")
fig.savefig(out / "hourly-profile.png", dpi=160)
plt.close(fig)
operating.reset_index().to_csv("operating-for-plots.csv", index=False)
plot_spec = {
"source": {"path": "operating-for-plots.csv", "table_id": "text:1", "header": True},
"charts": [
{"id": "hourly-observations", "type": "scatter", "x": "Hour", "y": count,
"title": "How much do individual observations vary by recorded hour?",
"x_label": "Recorded hour (time zone unknown)", "y_label": "Completed rentals", "y_unit": "rentals per hour"},
{"id": "hourly-distribution", "type": "histogram", "column": count, "bins": 24,
"title": "How common are high-volume operating hours?",
"x_label": "Completed rentals per operating hour", "y_label": "Number of operating hours"},
],
}
Path("plot-spec.json").write_text(json.dumps(plot_spec, indent=2), encoding="utf-8")
# Report metric definitions and source mapping
import json
from itertools import groupby
from pathlib import Path
from runpy import run_path
data = run_path("analyze.py")
df = data["df"]
operating = data["operating"]
suspended = data["suspended"]
all_hours = data["all_hours"]
day_hours = data["day_hours"]
season = data["season"]
count = data["count"]
state = data["state"]
source = "SeoulBikeData.csv"
full = f"{source} lines 2–{len(df) + 1}"
inspection = json.loads(Path("inspection.json").read_text())
table = inspection["tables"][0]
assert table["locator"]["line_range"] == [1, len(df) + 1]
assert table["n_cols"] == len(df.columns)
assert table["n_rows"] == len(df)
assert not inspection["read_extent"]["unread"]
assert [c["name"] for c in table["columns"]] == list(df.columns)
def ranges(rows):
spans = []
for _, group in groupby(enumerate(rows.index), lambda pair: pair[1] - pair[0]):
block = [line for _, line in group]
spans.append(str(block[0]) if len(block) == 1 else f"{block[0]}–{block[-1]}")
return f"{source} lines " + ", ".join(spans)
open_ref = ranges(operating)
closed_ref = ranges(suspended)
metrics = []
def metric(name, definition, value, unit, refs, numerator=None, denominator=None):
metrics.append(dict(name=name, definition=definition, value=value, unit=unit,
numerator=numerator, denominator=denominator, source_refs=refs,
depends_on_ambiguity_ids=[], condition=None))
return value
def mean(name, rows, selection, source_ref):
total = int(rows[count].sum())
hours = len(rows)
return metric(name, f"Sum of {count} divided by the number of operating rows, one per hour. {selection}.",
total / hours, "completed rentals per operating hour", [source_ref], total, hours)
def peak(group):
stats = all_hours if group is None else day_hours.loc[group]
hour = int(stats["mean"].idxmax())
rows = operating.loc[operating["Hour"].eq(hour)]
if group is not None:
rows = rows.loc[rows["Day type"].eq(group)]
value = mean(f"{group or 'Overall'} mean at {hour:02}:00", rows,
f"Highest mean over the 24 recorded hour labels within {group or 'all operating dates'}",
f"{open_ref}, filtered to Hour = {hour}" + (f" and Day type = {group}" if group else ""))
point = stats.loc[hour]
assert value == point["mean"] and len(rows) == point["hours"]
return hour, int(point["total"]), int(point["hours"]), value
overall_peak = peak(None)
weekday_peak = peak("Weekday")
weekend_peak = peak("Weekend")
mean("Overall operating-hour mean", operating, "All dates in the source", open_ref)
for group in ("Weekday", "Weekend"):
rows = operating.loc[operating["Hour"].eq(8) & operating["Day type"].eq(group)]
mean(f"{group} mean at 08:00", rows, f"{group} operating rows at Hour = 8",
f"{open_ref}, filtered to Hour = 8 and Day type = {group}")
for label in ("Spring", "Summer", "Autumn", "Winter"):
rows = operating.loc[operating["Seasons"].eq(label)]
result = mean(f"{label} operating-hour mean", rows, f"Operating rows labeled {label}",
f"{open_ref}, filtered to Seasons = {label}")
assert result == season.loc[label, "mean"]
for label, q in (("25th percentile", .25), ("Median operating hour", .5),
("75th percentile", .75), ("90th percentile", .9)):
metric(label, f"Quantile {q:g} of individual operating-hour counts, with linear interpolation.",
float(operating[count].quantile(q)), "completed rentals per operating hour", [open_ref])
metric("Service suspension hours", "Count of No rows, one per recorded hour.",
len(suspended), "hours", [closed_ref])
closed_by_date = suspended.groupby("Date").size()
metric("Dates affected by suspensions", "Count of distinct recorded dates with at least one No hour.",
len(closed_by_date), "recorded dates", [closed_ref])
metric("Fully suspended dates", "Count of recorded dates with all 24 rows marked No.",
int(closed_by_date.eq(24).sum()), "recorded dates", [closed_ref])
max_row = int(operating[count].idxmax())
max_value = int(operating.loc[max_row, count])
metric("Maximum observed hourly count", "Largest single operating-hour count in the supplied year.",
max_value, "completed rentals", [f"{source} line {max_row}"])
assert not operating.duplicated(["Date", "Hour"]).any()
assert all_hours["hours"].sum() == day_hours["hours"].sum() == season["hours"].sum() == len(operating)
assert all_hours["total"].sum() == day_hours["total"].sum() == season["total"].sum() == operating[count].sum()
assert operating["Holiday"].isin(["Holiday", "No Holiday"]).all()
excluded = f"{len(suspended):,} service suspension hours from the original CSV."
status_reason = f"Functioning Day = No on {len(suspended):,} rows."
h, total, n, v = overall_peak
wh, wt, wn, wv = weekday_peak
eh, et, en, ev = weekend_peak
profile_id = "hourly-profile"
chart_meta = {c["id"]: c for c in json.loads(Path("plot-results.json").read_text())}
for c in chart_meta.values():
assert c["n_used"] == len(operating) and c["n_excluded"] == 0
assert not c["missing_glyphs"] and not c["source_warnings"]
assert c["source_table_id"] == "text:1" and not c["read_extent"]["unread"]
def chart(chart_id, question, observation, interpretation):
meta = chart_meta[chart_id]
return dict(id=chart_id, question=question, type=meta["type"], source_columns=meta["source_columns"],
image_path=f"delivery/figures/{Path(meta['image_path']).name}", n_used=meta["n_used"],
n_excluded=len(suspended), exclusion_reason=status_reason, observation=observation,
domain_interpretation=interpretation, rendering_exclusions=meta["n_excluded"])
def log(i, item, evidence, status, answer, affects, question=None, candidates=()):
return dict(id=f"A{i:02}", checklist_item=item, question=question, file_evidence=evidence,
candidates=list(candidates), status=status, answer=answer, affects=affects)