File size: 6,265 Bytes
9349f93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | """
utils.py
--------
Shared utility helpers for the Sales Forecasting Dashboard.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from typing import List, Optional
# ---------------------------------------------------------------------------
# Formatting helpers
# ---------------------------------------------------------------------------
def format_number(n: float) -> str:
"""Return a human-readable string with comma thousands-separators.
Parameters
----------
n : float
The numeric value to format.
Returns
-------
str
e.g. ``"1,234,567.89"``
"""
try:
return f"{float(n):,.2f}"
except (TypeError, ValueError):
return str(n)
def format_currency(n: float, symbol: str = "$") -> str:
"""Return a currency-formatted string.
Parameters
----------
n : float
The numeric value to format.
symbol : str, optional
Currency symbol prefix (default ``"$"``).
Returns
-------
str
e.g. ``"$1,234,567.89"``
"""
return f"{symbol}{format_number(n)}"
def safe_divide(a: float, b: float, default: float = 0) -> float:
"""Safely divide *a* by *b*, returning *default* when *b* is zero.
Parameters
----------
a : float
Numerator.
b : float
Denominator.
default : float, optional
Value returned when *b* == 0 (default ``0``).
Returns
-------
float
``a / b`` or *default*.
"""
if b == 0:
return default
return a / b
def get_date_range_str(series: pd.Series) -> str:
"""Return a human-readable date-range string from a date series.
Parameters
----------
series : pd.Series
A series that can be coerced to datetime.
Returns
-------
str
e.g. ``"Jan 2021 – Dec 2023"``
"""
try:
dates = pd.to_datetime(series, errors="coerce").dropna()
if dates.empty:
return "Unknown"
start = dates.min().strftime("%b %Y")
end = dates.max().strftime("%b %Y")
return f"{start} \u2013 {end}"
except Exception:
return "Unknown"
# ---------------------------------------------------------------------------
# DataFrame helpers
# ---------------------------------------------------------------------------
def detect_categorical_columns(
df: pd.DataFrame,
exclude_cols: List[str],
max_unique: int = 50,
) -> List[str]:
"""Return column names that look categorical.
A column qualifies when it has ``object`` or ``category`` dtype, is **not**
in *exclude_cols*, and has at most *max_unique* distinct values.
Parameters
----------
df : pd.DataFrame
Source dataframe.
exclude_cols : list[str]
Column names to skip regardless of dtype.
max_unique : int, optional
Maximum number of unique values to still consider a column categorical
(default ``50``).
Returns
-------
list[str]
Qualifying column names.
"""
result: List[str] = []
exclude_set = set(exclude_cols)
for col in df.columns:
if col in exclude_set:
continue
if df[col].dtype.name in ("object", "category"):
if df[col].nunique(dropna=True) <= max_unique:
result.append(col)
return result
# ---------------------------------------------------------------------------
# Date / frequency helpers
# ---------------------------------------------------------------------------
def generate_future_dates(
last_date: pd.Timestamp,
periods: int,
freq: str,
) -> pd.DatetimeIndex:
"""Generate a :class:`pd.DatetimeIndex` of *periods* future dates.
Parameters
----------
last_date : pd.Timestamp
The last known date in the historical series.
periods : int
Number of future periods to generate.
freq : str
Pandas frequency alias (e.g. ``"D"``, ``"W"``, ``"MS"``).
Returns
-------
pd.DatetimeIndex
Index starting one period after *last_date*.
"""
return pd.date_range(start=last_date, periods=periods + 1, freq=freq)[1:]
def get_frequency_alias(freq_str: str) -> str:
"""Map a human-readable frequency label to its pandas alias.
Parameters
----------
freq_str : str
One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``.
Returns
-------
str
Pandas frequency string: ``"D"``, ``"W"``, or ``"MS"``.
Raises
------
ValueError
If *freq_str* is not recognised.
"""
norm = str(freq_str).strip().lower()
mapping = {
"daily": "D",
"d": "D",
"weekly": "W",
"w": "W",
"monthly": "MS",
"m": "MS",
"ms": "MS",
}
return mapping.get(norm, "D")
def robust_to_datetime(series: pd.Series) -> pd.Series:
"""Parse dates robustly across ISO, US (MM/DD/YYYY), UK/EU (DD/MM/YYYY), and mixed formats.
Tries standard datetime parsing first. If fewer than 80% parse successfully
(common when day comes first, e.g. Kaggle's Superstore data), it attempts
`dayfirst=True`, followed by `format='mixed'` where supported by pandas.
Parameters
----------
series : pd.Series
Series containing date strings or timestamps.
Returns
-------
pd.Series
Datetime-parsed series with invalid values coerced to NaT.
"""
if pd.api.types.is_datetime64_any_dtype(series):
return series
# 1. Standard parsing (fast, covers ISO 8601 like YYYY-MM-DD)
p1 = pd.to_datetime(series, errors="coerce")
rate1 = p1.notna().mean()
if rate1 >= 0.8:
return p1
# 2. Day-first parsing (covers DD/MM/YYYY common worldwide & Kaggle Superstore)
p2 = pd.to_datetime(series, dayfirst=True, errors="coerce")
rate2 = p2.notna().mean()
if rate2 >= rate1 and rate2 >= 0.8:
return p2
# 3. Mixed format parsing (pandas 2.0+)
try:
p3 = pd.to_datetime(series, format="mixed", errors="coerce")
rate3 = p3.notna().mean()
if rate3 >= rate2 and rate3 >= 0.8:
return p3
except Exception:
pass
# Return best parsed result
return p2 if rate2 > rate1 else p1
|