Data analysis assignment
Data analysis assignment
Purpose
From a data file and the assignment questions, build an executed Jupyter notebook plus HTML that an instructor can grade top to bottom. Each question ends with an answer whose numbers are printed by the code above it. Every changed row goes into one table with count and reason.
The AI does not invent values or causes the data cannot show, and does not fill gaps with the mean to smooth a plot. Unknown units, time zone or source stay `[check needed]`.
Input
- Required: the data file. If missing, ask only: "Please send the data file to analyze (CSV or Excel)."
- Helpful: question text, data notes (units, time zone, source), template, format, limits, due date.
- If your school or instructor gave you a template, that template comes first; these rules apply inside it.
- No questions given: use overview → cleaning → patterns → relations → conclusion, and say so.
- Never edit text the user marked "keep as is".
- Units, time zone or stamp meaning (does 01:00 hold 00–01 or 01–02?) unknown: ask once, then write `[check needed]` in Table 1 and go on.
Output
1. `analysis.py` (source), executed `analysis.ipynb`, `analysis.html`, `cleaning_log.csv`, figures `fig*.png` (200 dpi).
2. In the chat, "Points to check", 3–7 lines: rows received, rows dropped, added, interpolated, blank, flagged; `[check needed]` items; one or two key numbers; whether the notebook actually ran.
3. If Python cannot run here, give the files labeled "not run yet". Never describe outputs as if seen or compute answers by hand.
Rules
1. Steps
1) Copy the questions in order as headings, word for word.
2) Build Table 1. If expected and actual rows differ, find out why first.
3) Thresholds are first-cell constants, nowhere else.
4) Clean (section 3), then figure, table and answer per question.
5) Run `python make_notebook.py analysis.py`, open the HTML, run section 9.
2. Report on receipt (Table 1)
- Rows, period, expected rows, duplicate and missing stamps, units, time zone and stamp meaning, blanks per column, sentinel codes (9999, -999). This answers question 1.
- Expected rows per year: hourly 8,760 (leap year 8,784), 15-minute 35,040, daily 365.
- A numeric column read as text (`object`): report the mixed cells (often "61,234").
3. Gaps and outliers (Table 2)
- Order: duplicates → missing stamps → sentinels → impossible values → short gaps → long gaps → statistical outliers.
- Interpolate linearly only runs of 3 h or less; longer runs stay blank. Never fill with the mean or zero.
- Impossible values (demand ≤ 0, 1000× too large) are set blank, not rewritten. Dividing by 1000 needs a stated basis and a Table 2 line.
- Rare but possible values (price spikes) are flagged, never deleted: modified z-score > 5 against the monthly median (0.6745 × deviation / MAD). Monthly, so seasons are not flagged.
- Also report results without flagged rows: does the conclusion rest on a few rows?
- Table 2: check, rule, rows, action, reason. `assert` final rows = start − dropped + added.
- Daily means only for days with all 24 hours; state how many days were left out.
4. Notebook layout
- First code cell: constants, plot settings, library versions.
- Per question: heading "Question n. (text)" → code → output → **Answer**, 1–3 sentences.
- Answer numbers come from `display(Markdown(f"…"))`, never typed into Markdown.
- One job per cell; split at 40 lines. Code lines under 100 characters or the HTML cuts them.
- Relative paths (`data/…`), never `C:\Users\…`.
5. Figures
- Axis labels with quantity and unit: "Demand (MW)". Thousands separators (75,000).
- Title with number, period, source: "Figure 1. Mean by hour and season (2025-01-01 to 12-31, hypothetical data)".
- Hours 0–23, ticks every 3 h. Weekdays Mon to Sun.
- At most 4 lines per plot; with 2 or more, a legend plus a label at each peak. Color is never the only cue.
- No twin y-axes (`twinx`); demand and price go side by side.
- 8,760-point scatter: marker size 3, alpha 0.25, one panel per season, r and n in each title.
- A □ in a label means the font lacks that glyph (ρ, –); pick one that has it.
6. Correlation wording
- Pearson r and Spearman ρ together, with n and period.
- Recompute per season and say if it differs from the total.
- "Weak" or "strong" needs a cutoff (here |r| ≥ 0.7 is strong).
- Write "moved together". "Because", "drives" and "determines" need an experiment or model.
7. Answers (before → after)
- "It can be seen that price rises as demand increases." → "Hours with higher demand also had higher prices (r = 0.75, n = 8,748). Saying demand sets the price would need fuel cost data."
- "Outliers were removed to clean the data." → "Two price rows coded 9999 and three demand rows (a 0, two 1000× values) were set blank; 7 spike hours were flagged and kept (Table 2)."
- "Demand tends to decrease on weekends." → "Median Sunday daily mean demand is 9.7 % below Mon–Fri (Figure 2)."
8. The two files
Both were run end to end on a hypothetical case: 2025 hourly demand and price, 8,758 rows from seeded code, not a real market (KRW/kWh prices are hypothetical). Planted: 3 duplicates, 5 missing hours, two 9999 codes, a zero and two 1000× demand values, price spikes.
- `analysis.py`: source with `# %%` cell markers; VS Code opens it as cells and git diffs stay readable.
- `make_notebook.py`: runs `analysis.py` in a fresh kernel → `analysis.ipynb` → `analysis.html`. Stops if execution counts skip or a cell errors.
- Already in .ipynb? Restart & Run All, then `jupyter nbconvert --to html`.
9. Final check
- Table 1 complete; unknowns read `[check needed]`.
- Table 2 adds up (`assert` passed).
- Each figure has units, period, source, number; no twin axes.
- Each answer number matches the output above it.
- No correlation sentence implies cause.
- Execution counts run 1, 2, 3 … with no errors.
- You said whether you ran the notebook or only wrote files.
Attachment 1 · analysis.py (Python)
```python
%% [markdown]
# Hourly Demand and Price in a Power Market
Energy Systems Data Analysis, Assignment 2 · Alex Kim · 2026-12-05
#
- Data: `data/power_2025.csv`, 2025 hourly demand (MW) and price (KRW/kWh). **Hypothetical.**
- Each question ends with an **Answer**; its numbers are printed by the code above it.
- Run: Restart & Run All. Cleaning rules live only in the first code cell.
%%
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import Markdown, display
DATA = "data/power_2025.csv"
SENTINEL = 9999 # missing-value code in the raw file
DEMAND_OK_MW = (1, 200_000) # demand outside this range is impossible
SHORT_GAP_H = 3 # interpolate only blank runs of this many hours or fewer
Z_FLAG = 5 # flag (never delete) when monthly modified z exceeds this
SEASON = {12: "Winter", 1: "Winter", 2: "Winter", 6: "Summer", 7: "Summer", 8: "Summer"}
COLOR = {"Winter": "#257de0", "Summer": "#f47230", "Spring/Fall": "#00b894"}
NAME = {"demand_MW": "Demand", "price_won_per_kWh": "Price"}
UNIT = {"demand_MW": "MW", "price_won_per_kWh": "KRW/kWh"}
PERIOD = "2025-01-01 to 12-31, hypothetical data"
label = lambda c: f"{NAME[c]} ({UNIT[c]})"
plt.rcParams.update({
"font.family": "DejaVu Sans", "font.size": 9, "figure.dpi": 110, "savefig.dpi": 200,
"lines.linewidth": 2, "axes.grid": True, "grid.color": "#e7e7e7", "axes.edgecolor": "#c2c2c2",
"axes.spines.top": False, "axes.spines.right": False, "axes.axisbelow": True,
"xtick.color": "#666666", "ytick.color": "#666666"})
def show(t, caption, fmt=None, text=False):
st = t.rename_axis(index=None).style.set_caption(caption).format(fmt)
if text: # text tables left-aligned, number tables right
st = st.set_properties(**{"text-align": "left"}).set_table_styles(
[{"selector": "th", "props": "text-align: left;"}])
display(st)
print("pandas", pd.__version__, "| numpy", np.__version__, "| matplotlib", matplotlib.__version__)
%% [markdown]
## Question 1. How many rows, what period, what units, and what is missing?
%%
raw = pd.read_csv(DATA, parse_dates=["datetime"])
full = pd.date_range(raw.datetime.min(), raw.datetime.max(), freq="h")
gone = full.difference(raw.datetime)
t1 = pd.Series({
"Rows": f"{len(raw):,}",
"Period": f"{raw.datetime.min():%Y-%m-%d %H:%M} to {raw.datetime.max():%Y-%m-%d %H:%M}",
"Rows expected at 1 h steps": f"{len(full):,}",
"Duplicate timestamps": raw.datetime.duplicated().sum(),
"Missing timestamps": len(gone),
"Units (from column names)": "demand MW, price KRW/kWh",
"Time zone, stamp meaning": "local time, start of hour [check needed]",
"Blank demand": raw.demand_MW.isna().sum(),
"Blank price": raw.price_won_per_kWh.isna().sum(),
f"Price = {SENTINEL}": (raw.price_won_per_kWh == SENTINEL).sum()}, name="Value")
show(t1.to_frame(), "Table 1. Data as received", text=True)
display(Markdown(
f"**Answer** {t1['Rows']} rows, {t1['Period']}. 1 h steps need {len(full):,} rows; there are "
f"{t1['Duplicate timestamps']} duplicates and {len(gone)} missing hours. Blank: demand "
f"{t1['Blank demand']} h, price {t1['Blank price']} h."))
%% [markdown]
## Question 2. How were missing values and outliers handled?
Order: duplicates → missing hours → sentinel codes → impossible values → interpolate short
gaps → leave long gaps → statistical outliers (flag only).
%%
log = []
def note(check, rule, n, action, why):
log.append({"Check": check, "Rule": rule, "Rows": int(n), "Action": action, "Reason": why})
df = raw.drop_duplicates("datetime", keep="first")
note("Duplicate time", "same datetime twice", len(raw) - len(df), "drop 2nd row", "identical rows")
df = df.set_index("datetime").reindex(full)
note("Missing time", "absent at 1 h step", len(gone), "add blank row", "even time axis")
bad = df.price_won_per_kWh == SENTINEL
df.loc[bad, "price_won_per_kWh"] = np.nan
note("Sentinel", f"price = {SENTINEL}", bad.sum(), "set blank", "missing code in raw file")
lo, hi = DEMAND_OK_MW
bad = df.demand_MW.notna() & ~df.demand_MW.between(lo, hi)
df.loc[bad, "demand_MW"] = np.nan
note("Impossible", f"demand < {lo} or > {hi:,} MW", bad.sum(), "set blank",
"0 = meter dropout, x1000 = kW logged")
for c in NAME:
s = df[c]
run = s.isna().groupby(s.notna().cumsum()).transform("sum") # length of each blank run (h)
short = s.isna() & (run <= SHORT_GAP_H)
df[c] = s.interpolate(limit_area="inside").where(s.notna() | short)
note("Short gap", f"{NAME[c]}, <= {SHORT_GAP_H} h", short.sum(), "linear interp.",
"between neighbors")
note("Long gap", f"{NAME[c]}, >= {SHORT_GAP_H + 1} h", (s.isna() & ~short).sum(),
"leave blank", "filling invents a shape")
for c in NAME:
m = df.index.month # per month, so seasons are not called outliers
dev = df[c] - df[c].groupby(m).transform("median")
df[c + "_flag"] = (0.6745 * dev / dev.abs().groupby(m).transform("median")).abs() > Z_FLAG
note("Statistical", f"{NAME[c]}, monthly modified z > {Z_FLAG}", df[c + "_flag"].sum(),
"flag only", "spikes can be real")
%%
assert len(df) == len(raw) - log[0]["Rows"] + log[1]["Rows"] # do the Table 2 counts add up?
t2 = pd.DataFrame(log, index=pd.RangeIndex(1, len(log) + 1, name="Step"))
t2.to_csv("cleaning_log.csv", encoding="utf-8-sig")
show(t2, "Table 2. Cleaning log", text=True)
left = df[list(NAME)].isna().sum()
display(Markdown(
f"**Answer** From {len(raw):,} rows I dropped {log[0]['Rows']} duplicates and added "
f"{log[1]['Rows']} missing hours, giving {len(df):,} rows. Short gaps were interpolated: "
f"demand {log[4]['Rows']} h, price {log[6]['Rows']} h. Long gaps stay blank: demand "
f"{left.demand_MW} h, price {left.price_won_per_kWh} h. {log[9]['Rows']} price hours are "
"flagged as spikes and kept (Table 2)."))
%% [markdown]
## Question 3. How do demand and price change by hour, weekday, and season?
Seasons in this notebook: Winter = Dec–Feb, Summer = Jun–Aug, Spring/Fall = other months.
Daily means use only days with all 24 hours present.
%%
df["season"] = df.index.month.map(lambda m: SEASON.get(m, "Spring/Fall"))
prof = {c: df.pivot_table(index=df.index.hour, columns="season", values=c) for c in NAME}
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.5))
for ax, c in zip(axes, NAME):
for s, col in COLOR.items():
y = prof[c][s]
ax.plot(y.index, y, color=col, label=s)
ax.annotate(s, (y.idxmax(), y.max()), xytext=(0, 4), textcoords="offset points",
ha="center")
ax.set(xlabel="Hour of day (local time)", ylabel=label(c), xticks=range(0, 24, 3), xlim=(0, 23))
ax.margins(y=0.12)
ax.yaxis.set_major_formatter("{x:,.0f}")
fig.legend(*axes[0].get_legend_handles_labels(), loc="upper right", ncol=3, frameon=False)
fig.suptitle(f"Figure 1. Mean by hour and season ({PERIOD})", x=0.01, ha="left")
fig.tight_layout(); fig.savefig("fig1_hourly.png"); plt.show()
%%
ok = df[list(NAME)].resample("D").count() == 24 # days with no blank hour
day = df[list(NAME)].resample("D").mean().where(ok)
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.2))
for ax, c in zip(axes, NAME):
ax.boxplot([day.loc[day.index.dayofweek == d, c].dropna() for d in range(7)], widths=0.5,
medianprops={"color": "#191919"}, boxprops={"color": "#257de0"},
whiskerprops={"color": "#257de0"}, capprops={"color": "#257de0"},
flierprops={"markeredgecolor": "#666666", "markersize": 3})
ax.set_xticks(range(1, 8), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
ax.set(xlabel="Day of week", ylabel=f"Daily mean {NAME[c].lower()} ({UNIT[c]})")
ax.yaxis.set_major_formatter("{x:,.0f}")
fig.suptitle(f"Figure 2. Daily mean by weekday, box = quartiles, line = median ({PERIOD})",
x=0.01, ha="left")
fig.tight_layout(); fig.savefig("fig2_weekday.png"); plt.show()
%%
mean = df.groupby("season")[list(NAME)].mean()
t3 = pd.DataFrame({"Mean demand (MW)": mean.demand_MW,
"Demand peak hour": prof["demand_MW"].idxmax(),
"Mean price (KRW/kWh)": mean.price_won_per_kWh,
"Price low hour": prof["price_won_per_kWh"].idxmin()}).loc[list(COLOR)]
show(t3, "Table 3. Summary by season", "{:,.0f}")
med = day.demand_MW.groupby(day.index.dayofweek).median()
sun = (1 - med.loc[6] / med.loc[0:4].mean()) * 100 # Sun (6) vs Mon (0) to Fri (4)
top = t3["Mean demand (MW)"].idxmax()
each = ", ".join(f"{s} {v:,.0f} MW" for s, v in t3["Mean demand (MW)"].items())
display(Markdown(
f"**Answer** Mean demand is highest in {top} ({each}, Table 3). Demand peaks at "
f"{t3.iloc[0, 1]:.0f}:00 in Winter and {t3.iloc[1, 1]:.0f}:00 in Summer (Figure 1). The median "
f"Sunday daily mean is {sun:.1f} % below the average of the Mon–Fri medians (Figure 2). "
f"Spring/Fall price is lowest at {t3.iloc[2, 3]:.0f}:00. {(~ok).any(axis=1).sum()} days "
"with blank hours are left out of the daily means."))
%% [markdown]
## Question 4. How are demand and price related?
Pearson r measures a straight-line relation, Spearman ρ a rank relation.
Correlation says how two series move together; it does not show cause.
%%
both = df.dropna(subset=list(NAME))
corr = lambda g: pd.Series({
"n": len(g), "Pearson r": g.demand_MW.corr(g.price_won_per_kWh),
"Spearman ρ": g.demand_MW.corr(g.price_won_per_kWh, method="spearman")})
t4 = pd.DataFrame({"All": corr(both), **{s: corr(both[both.season == s]) for s in COLOR},
"All, spikes removed": corr(both[~both.price_won_per_kWh_flag])}).T
fig, axes = plt.subplots(1, 3, figsize=(9.6, 3.3), sharex=True, sharey=True)
for ax, (s, col) in zip(axes, COLOR.items()):
g = both[both.season == s]
f = g[g.price_won_per_kWh_flag]
ax.scatter(g.demand_MW, g.price_won_per_kWh, s=3, alpha=0.25, color=col, linewidths=0)
ax.scatter(f.demand_MW, f.price_won_per_kWh, s=18, facecolors="none", edgecolors="#191919",
lw=0.8)
ax.set_title(f"{s}: r = {t4.loc[s, 'Pearson r']:.2f}, n = {len(g):,}", loc="left", fontsize=9)
ax.set_xlabel(label("demand_MW"))
ax.xaxis.set_major_formatter("{x:,.0f}")
ax.locator_params(axis="x", nbins=4)
axes[0].set_ylabel(label("price_won_per_kWh"))
fig.suptitle(f"Figure 3. Hourly demand vs price, open circle = flagged spike ({PERIOD})",
x=0.01, ha="left")
fig.tight_layout(); fig.savefig("fig3_scatter.png"); plt.show()
show(t4, "Table 4. Demand–price correlation",
{"n": "{:,.0f}", "Pearson r": "{:.2f}", "Spearman ρ": "{:.2f}"})
r, rho = t4["Pearson r"], t4["Spearman ρ"]
display(Markdown(
f"**Answer** Hours with higher demand also had higher prices (r = {r['All']:.2f}, "
f"ρ = {rho['All']:.2f}, n = {len(both):,}, Table 4). By season: Winter r = {r['Winter']:.2f}, "
f"Summer {r['Summer']:.2f}, Spring/Fall {r['Spring/Fall']:.2f}. Without the "
f"{both.price_won_per_kWh_flag.sum()} flagged spikes, r = {r['All, spikes removed']:.2f}. "
"The data show only that the two move together; saying demand sets the price needs fuel cost "
"and generation mix data."))
%% [markdown]
## Question 5. Conclusions and limits
%%
display(Markdown("\n".join([
f"1. Mean demand was highest in {top} ({t3.iloc[:, 0].max():,.0f} MW); "
"the hour of peak demand differs by season (Table 3, Figure 1).",
f"2. Sunday daily mean demand was {sun:.1f} % below Mon–Fri (Figure 2).",
f"3. Demand–price correlation r = {r['All']:.2f}; by season "
f"{r[list(COLOR)].min():.2f} to {r[list(COLOR)].max():.2f} (Table 4). Cause was not tested.",
f"4. Limits: {left.demand_MW} blank demand hours are out of every calculation. Time zone and "
"stamp meaning are [check needed]. The data are hypothetical."])))
```
Attachment 2 · make_notebook.py (Python)
```python
make_notebook.py - analysis.py ("# %%" cells) -> analysis.ipynb run in a fresh kernel -> .html
Setup once: pip install nbformat nbclient nbconvert ipykernel. Run: python make_notebook.py analysis.py
import re
import sys
from pathlib import Path
import nbformat
from nbclient import NotebookClient
from nbconvert import HTMLExporter
src = Path(sys.argv[1])
cells = []
for block in re.split(r"^# %%", src.read_text(encoding="utf-8"), flags=re.M)[1:]:
head, _, body = block.partition("\n")
if "[markdown]" in head:
lines = [ln[2:] if ln.startswith("# ") else ln.lstrip("#") for ln in body.strip().splitlines()]
cells.append(nbformat.v4.new_markdown_cell("\n".join(lines)))
else:
cells.append(nbformat.v4.new_code_cell(body.strip()))
nb = nbformat.v4.new_notebook(cells=cells)
nb.metadata["kernelspec"] = {"name": "python3", "display_name": "Python 3", "language": "python"}
Same as Restart & Run All: new kernel, top to bottom, once. Any error stops here.
NotebookClient(nb, timeout=600, kernel_name="python3", resources={"metadata": {"path": str(src.parent.resolve())}}).execute()
code = [c for c in nb.cells if c.cell_type == "code"]
assert [c.execution_count for c in code] == list(range(1, len(code) + 1)), "execution count not 1..n"
assert not [o for c in code for o in c.outputs if o.output_type == "error"], "error output found"
nbformat.write(nb, src.with_suffix(".ipynb"))
html, _ = HTMLExporter(template_name="lab").from_notebook_node(nb)
src.with_suffix(".html").write_text(html, encoding="utf-8")
print(f"{src.with_suffix('.ipynb')}, {src.with_suffix('.html')}: {len(code)} code cells, run 1-{len(code)}, 0 errors")
```
Connect ChatGPT or Claude and use this prompt now · More prompts