wrapkit 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wrapkit/frames.py ADDED
@@ -0,0 +1,301 @@
1
+ """
2
+ DataFrame helpers shared by the wrappers: the tidy shape, polars, periods.
3
+
4
+ The opt-in tidy shape every wrapper offers is one row per observation with the
5
+ columns ``date``, then the source's dimension columns, then ``value`` (float64)
6
+ and ``unit`` (string, ``<NA>`` when unknown). Which columns are dimensions and
7
+ where the unit comes from is the wrapper's business; :func:`tidy_frame` applies
8
+ the shared column order, dtypes and sort.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import unicodedata
15
+ from typing import TYPE_CHECKING
16
+
17
+ import pandas as pd
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Sequence
21
+
22
+ import polars as pl
23
+
24
+ __all__ = [
25
+ "TIDY_VALUE_COLUMNS",
26
+ "as_polars",
27
+ "empty_tidy",
28
+ "period_end",
29
+ "period_start",
30
+ "snake",
31
+ "tidy_frame",
32
+ ]
33
+
34
+ #: The fixed trailing columns of the tidy shape.
35
+ TIDY_VALUE_COLUMNS = ("value", "unit")
36
+
37
+
38
+ def snake(name: str, *, acronyms: bool = False) -> str:
39
+ """
40
+ Convert a column name to snake_case.
41
+
42
+ Splits camelCase boundaries and turns any run of non-alphanumeric
43
+ characters into one underscore: ``stateDescription`` becomes
44
+ ``state_description`` and ``area-name`` becomes ``area_name``.
45
+
46
+ By default a run of capitals stays glued to the next word (``GDPValue``
47
+ becomes ``gdpvalue``). With ``acronyms`` the run is kept as a word of its
48
+ own: ``GDPValue`` becomes ``gdp_value`` and ``isCAMRelevant``
49
+ ``is_cam_relevant``.
50
+
51
+ Accents are dropped and German letters spelled out (``Região`` becomes
52
+ ``regiao``, ``Größe`` ``groesse``); other letters, such as ``ø``, are kept.
53
+
54
+ Args:
55
+ name (str): The raw column name.
56
+ acronyms (bool): Split a run of capitals from the word that follows.
57
+
58
+ Returns:
59
+ str: The lower-case snake_case name.
60
+ """
61
+ name = _plain_letters(name)
62
+ if acronyms:
63
+ name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)
64
+ spaced = re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", name)
65
+ return re.sub(r"[\W_]+", "_", spaced).strip("_").lower()
66
+
67
+
68
+ # German letters spelled out, as in "Groesse": an umlaut is its vowel plus "e".
69
+ # Other accents are just dropped.
70
+ _SPELLED_OUT = {u: unicodedata.normalize("NFKD", u)[0] + "e" for u in "äöüÄÖÜ"}
71
+ _SPELLED_OUT["ß"] = "ss"
72
+
73
+
74
+ def _plain_letters(name: str) -> str:
75
+ """
76
+ Drop accents and spell out German letters, keeping every other character.
77
+
78
+ Args:
79
+ name (str): A column name.
80
+
81
+ Returns:
82
+ str: ``name`` without combining marks, each umlaut spelled as its
83
+ vowel plus ``e`` and ``ß`` as ``ss``.
84
+ """
85
+ for letter, spelled in _SPELLED_OUT.items():
86
+ name = name.replace(letter, spelled)
87
+ decomposed = unicodedata.normalize("NFKD", name)
88
+ return "".join(c for c in decomposed if not unicodedata.combining(c))
89
+
90
+
91
+ def empty_tidy(dims: Sequence[str]) -> pd.DataFrame:
92
+ """
93
+ Return an empty frame in the tidy shape, with its dtypes.
94
+
95
+ Args:
96
+ dims (Sequence[str]): The dimension columns, in order.
97
+
98
+ Returns:
99
+ pd.DataFrame: Columns ``date``, ``dims``, ``value``, ``unit``.
100
+ """
101
+ return pd.DataFrame(
102
+ {
103
+ "date": pd.Series(dtype="datetime64[ns]"),
104
+ **{c: pd.Series(dtype="string") for c in dims},
105
+ "value": pd.Series(dtype="float64"),
106
+ "unit": pd.Series(dtype="string"),
107
+ }
108
+ )
109
+
110
+
111
+ def tidy_frame(frame: pd.DataFrame, dims: Sequence[str]) -> pd.DataFrame:
112
+ """
113
+ Put a frame into the tidy shape's column order, dtypes and row order.
114
+
115
+ ``date`` becomes ``datetime64[ns]``, the dimensions ``string``, ``value``
116
+ ``float64`` (unparseable values become NaN) and ``unit`` ``string`` with
117
+ blank units as ``<NA>``. A missing ``unit`` column is added as all
118
+ ``<NA>``. Rows are sorted by the dimensions, then ``date`` (stable), and
119
+ get a fresh index. Other columns are dropped.
120
+
121
+ Args:
122
+ frame (pd.DataFrame): A frame with ``date``, ``dims``, ``value`` and
123
+ optionally ``unit``.
124
+ dims (Sequence[str]): The dimension columns, in order.
125
+
126
+ Returns:
127
+ pd.DataFrame: The tidy frame (a new object; the input is not changed).
128
+ """
129
+ if frame.empty:
130
+ return empty_tidy(dims)
131
+ tidy = frame.copy()
132
+ tidy["date"] = pd.to_datetime(tidy["date"]).astype("datetime64[ns]")
133
+ for col in dims:
134
+ tidy[col] = tidy[col].astype("string")
135
+ tidy["value"] = pd.to_numeric(tidy["value"], errors="coerce").astype("float64")
136
+ unit = (
137
+ tidy["unit"] if "unit" in tidy.columns else pd.Series(pd.NA, index=tidy.index)
138
+ )
139
+ text = unit.astype("string")
140
+ # A blank unit carries no information: treat it as missing.
141
+ tidy["unit"] = text.mask(text.eq("").fillna(value=False))
142
+ return (
143
+ tidy[["date", *dims, *TIDY_VALUE_COLUMNS]]
144
+ .sort_values([*dims, "date"], kind="stable")
145
+ .reset_index(drop=True)
146
+ )
147
+
148
+
149
+ def as_polars(frame: pd.DataFrame, dist: str) -> pl.DataFrame:
150
+ """
151
+ Convert a pandas result to polars, importing polars lazily.
152
+
153
+ polars is an optional extra of every wrapper, so it is only imported when a
154
+ caller asks for ``as_polars=True``.
155
+
156
+ Args:
157
+ frame (pd.DataFrame): The pandas result.
158
+ dist (str): The wrapper's distribution name, for the install hint.
159
+
160
+ Returns:
161
+ pl.DataFrame: ``polars.from_pandas(frame)``.
162
+
163
+ Raises:
164
+ ImportError: If polars is not installed.
165
+ """
166
+ try:
167
+ import polars as pl
168
+ except ImportError as exc:
169
+ msg = f'polars is not installed; install it with pip install "{dist}[polars]"'
170
+ raise ImportError(msg) from exc
171
+ return pl.from_pandas(frame)
172
+
173
+
174
+ # A period label at year, quarter or month precision: 2024, 2024-Q2 (or
175
+ # 2024Q2), 2024-06 (or 202406) and the SDMX month 2024-M06 (or 2024M6). Other
176
+ # month spellings (2024-6, 2024/06, 06/2024, Jun 2024) are recognised by
177
+ # pandas' period parser (_month). pandas.Timestamp reads 2024-M06 as
178
+ # 2024-01-01 00:00:06, so that spelling must be caught here.
179
+ _YEAR = re.compile(r"^\s*(\d{4})\s*$")
180
+ _QUARTER = re.compile(r"^\s*(\d{4})-?Q([1-4])\s*$", re.IGNORECASE)
181
+ _MONTH = re.compile(
182
+ r"^\s*(\d{4})(?:-?(0[1-9]|1[0-2])|-?M(0?[1-9]|1[0-2]))\s*$", re.IGNORECASE
183
+ )
184
+ # A year joined to a letter code (2024-M13, 2024-S1, 2024-W23) that none of the
185
+ # above matched: pandas.Timestamp may read the digits as a time of day.
186
+ _CODED = re.compile(r"^\s*\d{4}-?[A-Za-z]\d*\s*$")
187
+
188
+
189
+ def _span(label: str) -> tuple[pd.Timestamp, pd.Timestamp] | None:
190
+ """
191
+ Return the start and exclusive end of a year, quarter or month label.
192
+
193
+ Args:
194
+ label (str): The period label.
195
+
196
+ Returns:
197
+ tuple[pd.Timestamp, pd.Timestamp] | None: ``(start, next_start)``, or
198
+ ``None`` when ``label`` is not at one of those precisions.
199
+ """
200
+ if m := _YEAR.match(label):
201
+ start = pd.Timestamp(year=int(m[1]), month=1, day=1)
202
+ return start, start + pd.DateOffset(years=1)
203
+ if m := _QUARTER.match(label):
204
+ start = pd.Timestamp(year=int(m[1]), month=3 * int(m[2]) - 2, day=1)
205
+ return start, start + pd.DateOffset(months=3)
206
+ if m := _MONTH.match(label):
207
+ start = pd.Timestamp(year=int(m[1]), month=int(m[2] or m[3]), day=1)
208
+ return start, start + pd.DateOffset(months=1)
209
+ if (first := _month(label)) is not None:
210
+ return first, first + pd.DateOffset(months=1)
211
+ return None
212
+
213
+
214
+ def _month(label: str) -> pd.Timestamp | None:
215
+ """
216
+ Return the first day of a month label in another spelling.
217
+
218
+ ``2024-6``, ``2024/06``, ``06/2024``, ``2024.06`` and ``Jun 2024`` name a
219
+ month; :func:`pandas.Timestamp` would read each as the month's first day,
220
+ so an end bound would stop there. :class:`pandas.Period` infers the
221
+ precision instead (a full date stays a day).
222
+
223
+ Args:
224
+ label (str): The period label.
225
+
226
+ Returns:
227
+ pd.Timestamp | None: The month's first day, or ``None`` when the label
228
+ is not a month.
229
+ """
230
+ try:
231
+ period = pd.Period(label.strip())
232
+ except (ValueError, TypeError):
233
+ return None
234
+ if not isinstance(period, pd.Period) or period.freqstr != "M":
235
+ return None # NaT (an empty label) or another precision
236
+ return pd.Timestamp(year=period.year, month=period.month, day=1)
237
+
238
+
239
+ def period_start(label: str) -> pd.Timestamp:
240
+ """
241
+ Return the first instant of a period label.
242
+
243
+ Args:
244
+ label (str): ``2024``, ``2024-Q2``, a month (``2024-06``, ``2024-6``,
245
+ ``06/2024``, ``Jun 2024``, ``2024-M06``) or anything :func:`pandas.Timestamp`
246
+ parses (``2024-06-15``, ``2024-06-15T12:00``).
247
+
248
+ Returns:
249
+ pd.Timestamp: The start of the period. An unparseable label raises
250
+ ``ValueError``.
251
+ """
252
+ span = _span(label)
253
+ return span[0] if span else _parse(label)
254
+
255
+
256
+ def period_end(label: str) -> pd.Timestamp:
257
+ """
258
+ Return the exclusive end of a period label: an end bound covers its period.
259
+
260
+ The shared "end" rule: ``end="2024"`` means up to the end of 2024, so the
261
+ exclusive bound is 2025-01-01; ``2024-Q2`` ends at 2024-07-01 and
262
+ ``2024-06`` at 2024-07-01. A full date or timestamp is returned as given:
263
+ the wrapper decides whether a day bound is inclusive.
264
+
265
+ Args:
266
+ label (str): A period label (see :func:`period_start`).
267
+
268
+ Returns:
269
+ pd.Timestamp: The first instant after a year, quarter or month label,
270
+ or the parsed timestamp itself. An unparseable label raises
271
+ ``ValueError``.
272
+ """
273
+ span = _span(label)
274
+ return span[1] if span else _parse(label)
275
+
276
+
277
+ def _parse(label: str) -> pd.Timestamp:
278
+ """
279
+ Parse a date or timestamp label.
280
+
281
+ Args:
282
+ label (str): The label.
283
+
284
+ Returns:
285
+ pd.Timestamp: The parsed value.
286
+
287
+ Raises:
288
+ ValueError: If pandas cannot parse it.
289
+ """
290
+ if _CODED.match(label):
291
+ msg = f"Cannot parse period {label!r}."
292
+ raise ValueError(msg)
293
+ try:
294
+ value = pd.Timestamp(label.strip())
295
+ except (ValueError, TypeError) as exc:
296
+ msg = f"Cannot parse period {label!r}."
297
+ raise ValueError(msg) from exc
298
+ if pd.isna(value):
299
+ msg = f"Cannot parse period {label!r}."
300
+ raise ValueError(msg)
301
+ return value