sl-protostar-climate-ceviche / code /01_cdd_shift_table.py
sleonca's picture
Upload folder using huggingface_hub
b47743b verified
Raw History Blame Contribute Delete
1.03 kB
"""Precompute, for every city and year up to 2018, the CDD and hottest day that year's daily
temperatures would give if every day were shifted by delta °F (delta = -2 .. +8 by 0.25).
Writes data/processed/shift_table.parquet. Reads only the challenge daily data (<= 2018-12-31).
"""
import numpy as np, pandas as pd
from common import load_daily, ROOT
DELTAS = np.round(np.arange(-2, 8.0001, 0.25), 2)
d = load_daily()
d = d.dropna(subset=["tmax", "tmin"])
tavg = ((d.tmax + d.tmin) / 2).to_numpy()
key = d[["ID", "Year"]]
out = key.drop_duplicates().reset_index(drop=True)
g = pd.MultiIndex.from_frame(key)
cols = {}
for dl in DELTAS:
s = pd.Series(np.maximum(0, tavg + dl - 65), index=g).groupby(level=[0, 1]).sum()
cols[f"cdd_{dl:+.2f}"] = s
tab = pd.DataFrame(cols).reset_index()
tab["n_both"] = pd.Series(1, index=g).groupby(level=[0, 1]).sum().values
p = ROOT / "data" / "processed"; p.mkdir(parents=True, exist_ok=True)
tab.to_parquet(p / "shift_table.parquet", index=False)
print(tab.shape, tab.Year.max())