eolas-data 1.10.0__tar.gz → 1.11.0__tar.gz

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.
Files changed (56) hide show
  1. {eolas_data-1.10.0 → eolas_data-1.11.0}/CHANGELOG.md +13 -0
  2. {eolas_data-1.10.0 → eolas_data-1.11.0}/PKG-INFO +1 -1
  3. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/__init__.py +6 -1
  4. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/exceptions.py +35 -13
  5. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/meta.py +9 -0
  6. eolas_data-1.11.0/eolas_data/reshape.py +425 -0
  7. {eolas_data-1.10.0 → eolas_data-1.11.0}/pyproject.toml +1 -1
  8. eolas_data-1.11.0/tests/test_reshape.py +403 -0
  9. eolas_data-1.11.0/tests/test_reshape_integration.py +233 -0
  10. {eolas_data-1.10.0 → eolas_data-1.11.0}/.github/workflows/catalog-drift.yml +0 -0
  11. {eolas_data-1.10.0 → eolas_data-1.11.0}/.github/workflows/pre-release.yml +0 -0
  12. {eolas_data-1.10.0 → eolas_data-1.11.0}/.github/workflows/publish.yml +0 -0
  13. {eolas_data-1.10.0 → eolas_data-1.11.0}/.github/workflows/smoke.yml +0 -0
  14. {eolas_data-1.10.0 → eolas_data-1.11.0}/.github/workflows/test.yml +0 -0
  15. {eolas_data-1.10.0 → eolas_data-1.11.0}/.gitignore +0 -0
  16. {eolas_data-1.10.0 → eolas_data-1.11.0}/LICENSE +0 -0
  17. {eolas_data-1.10.0 → eolas_data-1.11.0}/README.md +0 -0
  18. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/_dataset_names.py +0 -0
  19. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/_regen_names.py +0 -0
  20. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/cdc.py +0 -0
  21. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/cli.py +0 -0
  22. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/client.py +0 -0
  23. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/console.py +0 -0
  24. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/dataset.py +0 -0
  25. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/library.py +0 -0
  26. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/mcp_server.py +0 -0
  27. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/rows.py +0 -0
  28. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/schedule.py +0 -0
  29. {eolas_data-1.10.0 → eolas_data-1.11.0}/eolas_data/search.py +0 -0
  30. {eolas_data-1.10.0 → eolas_data-1.11.0}/scripts/check_client_contract.py +0 -0
  31. {eolas_data-1.10.0 → eolas_data-1.11.0}/scripts/preflight.sh +0 -0
  32. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/fixtures/source_helpers.json +0 -0
  33. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_as_arrow.py +0 -0
  34. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_cdc_roundtrip.py +0 -0
  35. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_changes_http.py +0 -0
  36. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_cli.py +0 -0
  37. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_client.py +0 -0
  38. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_date_filter.py +0 -0
  39. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_geometry_param.py +0 -0
  40. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_get_local.py +0 -0
  41. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_keyring.py +0 -0
  42. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_library.py +0 -0
  43. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_mcp_integration.py +0 -0
  44. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_mcp_protocol.py +0 -0
  45. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_mcp_server.py +0 -0
  46. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_meta.py +0 -0
  47. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_preview_dimensions.py +0 -0
  48. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_progress.py +0 -0
  49. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_resilience.py +0 -0
  50. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_rows.py +0 -0
  51. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_schedule.py +0 -0
  52. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_search.py +0 -0
  53. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_smoke_live.py +0 -0
  54. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_source_helpers.py +0 -0
  55. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_sync_bulk.py +0 -0
  56. {eolas_data-1.10.0 → eolas_data-1.11.0}/tests/test_sync_changes.py +0 -0
@@ -3,6 +3,19 @@
3
3
  All notable changes to `eolas-data` are recorded here. This project follows
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 1.11.0
7
+
8
+ ### Added
9
+
10
+ - **`pivot_longer()` / `pivot_wider()` — client-side long/wide reshape.** Explicit,
11
+ module-level functions (never called automatically by `Client.get()`). They read the
12
+ new server-side `layout` metadata (`long`/`wide`/`feature`/`entity` + id/value/measure
13
+ columns) and **refuse rather than guess**: a `ReshapeError` when a table has no layout
14
+ metadata, or a `feature`/`entity` layout, or a geometry column present. `pivot_longer`
15
+ reattaches each measure's `series_id` on the melt; `pivot_wider` raises on non-unique
16
+ keys instead of silently collapsing. Both re-declare the reshaped frame's new layout so
17
+ `longer`↔`wider` round-trips. Re-aligns the version line with `eolas` (R) at 1.11.0.
18
+
6
19
  ## 1.10.0
7
20
 
8
21
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: eolas-data
3
- Version: 1.10.0
3
+ Version: 1.11.0
4
4
  Summary: Python client for the eolas.fyi statistical data API (NZ + OECD; Australia on roadmap)
5
5
  Project-URL: Homepage, https://eolas.fyi
6
6
  Project-URL: Documentation, https://docs.eolas.fyi/
@@ -16,8 +16,10 @@ from .exceptions import (
16
16
  EolasError,
17
17
  NotFoundError,
18
18
  RateLimitError,
19
+ ReshapeError,
19
20
  WatermarkExpired,
20
21
  )
22
+ from .reshape import pivot_longer, pivot_wider
21
23
 
22
24
  # Single source of truth: read the installed distribution's version so
23
25
  # __version__, `eolas version`, and the User-Agent can never drift from
@@ -26,7 +28,7 @@ from .exceptions import (
26
28
  try:
27
29
  __version__ = _pkg_version("eolas-data")
28
30
  except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
29
- __version__ = "1.10.0"
31
+ __version__ = "1.11.0"
30
32
 
31
33
  __all__ = [
32
34
  "Client",
@@ -44,4 +46,7 @@ __all__ = [
44
46
  "ChangesUpgradeRequired",
45
47
  "ChangesLicenceRestricted",
46
48
  "WatermarkExpired",
49
+ "ReshapeError",
50
+ "pivot_longer",
51
+ "pivot_wider",
47
52
  ]
@@ -26,13 +26,17 @@ class APIError(EolasError):
26
26
  # specifically can match the narrower type).
27
27
  # ---------------------------------------------------------------------------
28
28
 
29
+
29
30
  class BulkUpgradeRequired(APIError):
30
31
  """Raised on HTTP 402: the requested freshness level requires a Pro plan."""
31
32
 
32
- def __init__(self, message: str = (
33
- "Fresh bulk downloads are a Pro feature. Free accounts get the latest "
34
- "monthly snapshot — see https://eolas.fyi/pricing."
35
- )):
33
+ def __init__(
34
+ self,
35
+ message: str = (
36
+ "Fresh bulk downloads are a Pro feature. Free accounts get the latest "
37
+ "monthly snapshot — see https://eolas.fyi/pricing."
38
+ ),
39
+ ):
36
40
  super().__init__(402, message)
37
41
 
38
42
 
@@ -50,11 +54,14 @@ class BulkLicenceRestricted(APIError):
50
54
  class BulkNotYetAvailable(APIError):
51
55
  """Raised on HTTP 503: the monthly snapshot for this dataset does not exist yet."""
52
56
 
53
- def __init__(self, message: str = (
54
- "Monthly bulk snapshots are still rolling out for this dataset. "
55
- "Try again after the 1st of next month, or upgrade to Pro for "
56
- "on-demand current snapshots — see https://eolas.fyi/pricing."
57
- )):
57
+ def __init__(
58
+ self,
59
+ message: str = (
60
+ "Monthly bulk snapshots are still rolling out for this dataset. "
61
+ "Try again after the 1st of next month, or upgrade to Pro for "
62
+ "on-demand current snapshots — see https://eolas.fyi/pricing."
63
+ ),
64
+ ):
58
65
  super().__init__(503, message)
59
66
 
60
67
 
@@ -62,13 +69,17 @@ class BulkNotYetAvailable(APIError):
62
69
  # CDC / changelog-specific exceptions
63
70
  # ---------------------------------------------------------------------------
64
71
 
72
+
65
73
  class ChangesUpgradeRequired(APIError):
66
74
  """Raised on HTTP 402 from /changes: changelog sync requires Pro or higher."""
67
75
 
68
- def __init__(self, message: str = (
69
- "Changelog sync is a Pro feature. "
70
- "Upgrade at https://eolas.fyi/pricing or use sync_bulk() instead."
71
- )):
76
+ def __init__(
77
+ self,
78
+ message: str = (
79
+ "Changelog sync is a Pro feature. "
80
+ "Upgrade at https://eolas.fyi/pricing or use sync_bulk() instead."
81
+ ),
82
+ ):
72
83
  super().__init__(402, message)
73
84
 
74
85
 
@@ -79,6 +90,17 @@ class ChangesLicenceRestricted(APIError):
79
90
  super().__init__(403, message)
80
91
 
81
92
 
93
+ class ReshapeError(EolasError):
94
+ """Raised by :func:`eolas_data.reshape.pivot_longer`/`pivot_wider`.
95
+
96
+ Deliberate refusal, not a fallback to inference: a dataset with no
97
+ `layout` metadata, a `layout` of `"feature"`/`"entity"`, or a geometry
98
+ column present all raise this rather than guessing a date/period/value
99
+ shape. Mirrors the reasoning behind removing `Dataset.plot_dataset()` /
100
+ R's `eolas_plot()` in v1.3.0 — see `dataset.py`.
101
+ """
102
+
103
+
82
104
  class WatermarkExpired(APIError):
83
105
  """Raised on HTTP 410 from /changes: since_seq predates the retained changelog range.
84
106
 
@@ -59,6 +59,15 @@ _TABLE_META_KEYS = (
59
59
  "last_refreshed_at",
60
60
  "previous_snapshots",
61
61
  "date_filter_column",
62
+ # Long/wide reshape contract (2026-07-27) — consumed by
63
+ # eolas_data.reshape.pivot_longer()/pivot_wider(). Without these in the
64
+ # allowlist they would be silently dropped by split_meta() before ever
65
+ # reaching df.attrs["eolas_meta"], even though the API returns them.
66
+ "layout",
67
+ "time_columns",
68
+ "id_columns",
69
+ "value_columns",
70
+ "measure_name_column",
62
71
  )
63
72
 
64
73
  # Mirrors app/streaming.py::detect_date_col — columns that /data?start=&end= filter on.
@@ -0,0 +1,425 @@
1
+ """Client-side long/wide reshape helpers (2026-07-27).
2
+
3
+ ``pivot_longer()`` / ``pivot_wider()`` reshape a DataFrame returned by
4
+ :meth:`Client.get` or :meth:`Client.get_local` using the ``layout`` /
5
+ ``time_columns`` / ``id_columns`` / ``value_columns`` / ``measure_name_column``
6
+ metadata attached to it (see ``eolas_data.meta.attach_meta``).
7
+
8
+ These are deliberately **explicit, separate functions** — they are never
9
+ called automatically by :meth:`Client.get` / :meth:`Client.get_local`, and
10
+ they **refuse** rather than guess a shape:
11
+
12
+ * No ``layout`` metadata attached (and none derivable via ``name=``/``client=``)
13
+ → :class:`~eolas_data.exceptions.ReshapeError`.
14
+ * ``layout in ("feature", "entity")`` → refuse (a feature/entity row is the
15
+ natural grain; melting or pivoting is meaningless).
16
+ * A geometry column (``geometry_wkt`` string, or an active GeoDataFrame
17
+ geometry column) is present → refuse (melting geometry repeats the
18
+ WKT/WKB payload once per measure row).
19
+
20
+ This mirrors the reasoning that led to ``Dataset.plot_dataset()`` (and R's
21
+ ``eolas_plot()``) being removed in v1.3.0 — see ``dataset.py``: eolas does not
22
+ ship a helper that has to *guess* per-dataset shape from column names like
23
+ ``date``/``period``/``value``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import TYPE_CHECKING, Any, Optional, Sequence
29
+
30
+ import pandas as pd
31
+
32
+ from .exceptions import ReshapeError
33
+
34
+ if TYPE_CHECKING: # pragma: no cover
35
+ from .client import Client
36
+
37
+ __all__ = ["pivot_longer", "pivot_wider"]
38
+
39
+ _GEOMETRY_COLUMNS = {"geometry_wkt", "geometry"}
40
+
41
+
42
+ def _is_geodataframe(df: pd.DataFrame) -> bool:
43
+ try:
44
+ import geopandas as gpd
45
+ except ImportError:
46
+ return False
47
+ return isinstance(df, gpd.GeoDataFrame)
48
+
49
+
50
+ def _frame_attr(df: pd.DataFrame, key: str) -> Any:
51
+ """Read an eolas attribute — checks `.attrs` (always set, incl. GeoDataFrame)
52
+ before the object attribute (set for plain Dataset/DataFrame only — see
53
+ meta.attach_meta, which skips object.__setattr__ for GeoDataFrames)."""
54
+ attrs = getattr(df, "attrs", None)
55
+ if isinstance(attrs, dict) and key in attrs and attrs[key] not in (None, {}):
56
+ return attrs[key]
57
+ return getattr(df, key, None)
58
+
59
+
60
+ def _as_list(v: Any) -> list:
61
+ if v is None:
62
+ return []
63
+ if isinstance(v, (list, tuple, set)):
64
+ return list(v)
65
+ return [v]
66
+
67
+
68
+ def _dataset_label(df: pd.DataFrame, name: Optional[str]) -> str:
69
+ return name or _frame_attr(df, "eolas_name") or "this dataset"
70
+
71
+
72
+ def _attach_reshaped_meta(
73
+ out: pd.DataFrame,
74
+ src: pd.DataFrame,
75
+ *,
76
+ layout: str,
77
+ time_columns: list,
78
+ id_columns: list,
79
+ value_columns: list,
80
+ measure_name_column: str,
81
+ ) -> pd.DataFrame:
82
+ """Rewrite the eolas layout metadata on a reshaped frame so it describes the
83
+ NEW shape, not the source shape. Without this a `pivot_longer(wide)` result
84
+ still says `layout="wide"` and `pivot_wider()` on it wrongly errors
85
+ "already wide" — the round-trip is only usable if the result re-declares
86
+ itself long/wide. pandas melt/pivot do not carry `.attrs` reliably, so we
87
+ set them explicitly."""
88
+ out.attrs["eolas_meta"] = {
89
+ "layout": layout,
90
+ "time_columns": [c for c in time_columns if c in out.columns],
91
+ "id_columns": [c for c in id_columns if c in out.columns],
92
+ "value_columns": value_columns,
93
+ "measure_name_column": measure_name_column,
94
+ }
95
+ name = _frame_attr(src, "eolas_name")
96
+ if name:
97
+ out.attrs["eolas_name"] = name
98
+ return out
99
+
100
+
101
+ def _series_id_map(column_meta: Any) -> dict:
102
+ """Column-name -> series_id from the eolas_columns glossary, if any."""
103
+ if column_meta is None:
104
+ return {}
105
+ if isinstance(column_meta, pd.DataFrame):
106
+ if column_meta.empty or "series_id" not in column_meta.columns:
107
+ return {}
108
+ records = column_meta.to_dict("records")
109
+ elif isinstance(column_meta, list):
110
+ records = column_meta
111
+ else:
112
+ return {}
113
+ out: dict[str, str] = {}
114
+ for rec in records:
115
+ if not isinstance(rec, dict):
116
+ continue
117
+ sid = rec.get("series_id")
118
+ col = rec.get("name")
119
+ if sid and col:
120
+ out[col] = sid
121
+ return out
122
+
123
+
124
+ def _get_eolas_meta(
125
+ df: pd.DataFrame,
126
+ *,
127
+ name: Optional[str] = None,
128
+ client: Optional["Client"] = None,
129
+ ) -> dict:
130
+ """Resolve the DatasetMeta dict attached to `df`, or fetch it by name.
131
+
132
+ Checked in order: `df.attrs["eolas_meta"]` / `df.eolas_meta` (attached by
133
+ Client.get()/get_local() with meta=True — the default, on BOTH the live
134
+ and bulk-cache paths, since both funnel through
135
+ Client._attach_dataset_meta -> meta.split_meta/attach_meta). Falls back to
136
+ a fresh `client.info(name)` call when nothing is attached (e.g.
137
+ meta=False was used, or `df` was loaded from disk with no attrs).
138
+ """
139
+ meta = _frame_attr(df, "eolas_meta")
140
+ if not meta:
141
+ ds_name = name or _frame_attr(df, "eolas_name")
142
+ if ds_name and client is not None:
143
+ try:
144
+ meta = client.info(ds_name)
145
+ except Exception:
146
+ meta = None
147
+ if not meta:
148
+ raise ReshapeError(
149
+ "Cannot reshape: no eolas layout metadata attached to this DataFrame. "
150
+ "Pass a frame from Client.get()/get_local() with meta=True (the "
151
+ "default), or call pivot_longer(df, name=..., client=...) / "
152
+ "pivot_wider(df, name=..., client=...) to fetch it directly."
153
+ )
154
+ return meta
155
+
156
+
157
+ def _reshape_guard(df: pd.DataFrame, meta: dict, *, name: Optional[str] = None) -> str:
158
+ """Shared refusal gate for pivot_longer()/pivot_wider(). Returns the
159
+ lower-cased layout string on success; raises ReshapeError otherwise."""
160
+ ds_name = _dataset_label(df, name)
161
+ layout = meta.get("layout")
162
+ if not layout:
163
+ raise ReshapeError(
164
+ f"Cannot reshape {ds_name!r}: no `layout` metadata. eolas refuses to "
165
+ "guess a date/period/value shape from column names — this is exactly "
166
+ "the silent-wrongness class Dataset.plot_dataset() was removed for "
167
+ "in v1.3.0. See https://docs.eolas.fyi for the layout contract."
168
+ )
169
+ layout = str(layout).strip().lower()
170
+ if layout in ("feature", "entity"):
171
+ kind = (
172
+ "a feature table (one row per real-world entity, e.g. a parcel or "
173
+ "address)"
174
+ if layout == "feature"
175
+ else "an entity table (one row per case/claim/award)"
176
+ )
177
+ raise ReshapeError(
178
+ f"Cannot reshape {ds_name!r}: layout is {layout!r} — {kind}. "
179
+ "Melting or pivoting would be meaningless."
180
+ )
181
+ if any(c in df.columns for c in _GEOMETRY_COLUMNS) or _is_geodataframe(df):
182
+ raise ReshapeError(
183
+ f"Cannot reshape {ds_name!r}: a geometry column is present. Melting "
184
+ "geometry repeats the WKT/WKB payload once per measure row — drop it "
185
+ "first with geometry=False on the fetch call."
186
+ )
187
+ return layout
188
+
189
+
190
+ def pivot_longer(
191
+ df: pd.DataFrame,
192
+ *,
193
+ names_to: Optional[str] = None,
194
+ values_to: str = "value",
195
+ name: Optional[str] = None,
196
+ client: Optional["Client"] = None,
197
+ ) -> pd.DataFrame:
198
+ """Reshape a wide eolas DataFrame to long format.
199
+
200
+ Melts the dataset's ``value_columns`` (from the ``layout`` metadata
201
+ attached by :meth:`Client.get` / :meth:`Client.get_local`) into a
202
+ measure-name column and a value column. Requires ``layout == "wide"``
203
+ metadata — see the module docstring for the full refusal list.
204
+
205
+ If the wide table's columns carry a per-column ``series_id`` mapping
206
+ (the ``eolas_columns`` glossary attribute — see
207
+ :meth:`Dataset.column_label`), a ``series_id`` column is added to the
208
+ result mapping each measure back to its original series id.
209
+
210
+ Args:
211
+ df: A DataFrame from ``Client.get()``/``Client.get_local()`` with
212
+ ``layout = "wide"`` metadata attached.
213
+ names_to: Name of the output column holding the former column
214
+ names. ``None`` (default) uses the dataset's
215
+ ``measure_name_column`` metadata, falling back to ``"measure"``.
216
+ values_to: Name of the output value column. Default ``"value"``.
217
+ name: Dataset identifier, used only to fetch metadata when `df` has
218
+ none attached. Not required when `df` carries ``eolas_meta``.
219
+ client: A :class:`Client` instance, used only with `name` to fetch
220
+ metadata when none is attached.
221
+
222
+ Returns:
223
+ A long-format ``pd.DataFrame``.
224
+
225
+ Raises:
226
+ ReshapeError: no layout metadata, layout is ``feature``/``entity``,
227
+ a geometry column is present, layout is not ``wide``, or none of
228
+ the metadata ``value_columns`` are present in `df`.
229
+
230
+ Example:
231
+ >>> wide = client.get("rbnz_b1_exchange_rates_monthly")
232
+ >>> long = pivot_longer(wide)
233
+ """
234
+ meta = _get_eolas_meta(df, name=name, client=client)
235
+ layout = _reshape_guard(df, meta, name=name)
236
+ ds_name = _dataset_label(df, name)
237
+
238
+ if layout != "wide":
239
+ hint = (
240
+ " This dataset is already long — see pivot_wider() to go the " "other way."
241
+ if layout == "long"
242
+ else ""
243
+ )
244
+ raise ReshapeError(
245
+ f"Cannot pivot_longer {ds_name!r}: layout is {layout!r}, not "
246
+ f"'wide'.{hint}"
247
+ )
248
+
249
+ value_cols = [c for c in _as_list(meta.get("value_columns")) if c in df.columns]
250
+ if not value_cols:
251
+ raise ReshapeError(
252
+ f"Cannot pivot_longer {ds_name!r}: none of the metadata "
253
+ "`value_columns` are present in this DataFrame. The schema may "
254
+ "have changed since metadata was cached; try force=True on the "
255
+ "fetch call."
256
+ )
257
+ id_cols = [
258
+ c
259
+ for c in _as_list(meta.get("id_columns"))
260
+ if c in df.columns and c not in value_cols
261
+ ]
262
+ if not id_cols:
263
+ id_cols = [c for c in df.columns if c not in value_cols]
264
+
265
+ measure_col = names_to or meta.get("measure_name_column") or "measure"
266
+
267
+ out = df.melt(
268
+ id_vars=id_cols,
269
+ value_vars=value_cols,
270
+ var_name=measure_col,
271
+ value_name=values_to,
272
+ )
273
+ out = out.dropna(subset=[values_to]).reset_index(drop=True)
274
+
275
+ sid_map = _series_id_map(_frame_attr(df, "eolas_columns"))
276
+ if sid_map and "series_id" not in out.columns:
277
+ out["series_id"] = out[measure_col].map(sid_map)
278
+
279
+ # Result is now long — re-declare it so pivot_wider() can reverse it.
280
+ return _attach_reshaped_meta(
281
+ out,
282
+ df,
283
+ layout="long",
284
+ time_columns=_as_list(meta.get("time_columns")),
285
+ id_columns=id_cols,
286
+ value_columns=[values_to],
287
+ measure_name_column=measure_col,
288
+ )
289
+
290
+
291
+ def pivot_wider(
292
+ df: pd.DataFrame,
293
+ *,
294
+ names_from: Optional[str] = None,
295
+ values_from: Optional[str] = None,
296
+ id_cols: Optional[Sequence[str]] = None,
297
+ values_fill: Optional[Any] = None,
298
+ name: Optional[str] = None,
299
+ client: Optional["Client"] = None,
300
+ ) -> pd.DataFrame:
301
+ """Reshape a long eolas DataFrame to wide format.
302
+
303
+ Spreads one long-format value column into multiple columns keyed by a
304
+ "names" column. Requires ``layout == "long"`` metadata — see the module
305
+ docstring for the full refusal list.
306
+
307
+ Unlike ``pivot_longer``, this never has a bare "always safe" default: a
308
+ long table with more than one dimension column can legitimately be
309
+ pivoted on several different keys, and picking the wrong one silently
310
+ produces a cartesian blow-up (one row per id-combination x measure,
311
+ mostly ``NaN``). ``names_from``/``values_from`` must therefore be either
312
+ supplied explicitly, or unambiguously derivable — a single
313
+ ``value_columns`` entry plus a ``measure_name_column`` in the attached
314
+ metadata.
315
+
316
+ Args:
317
+ df: A DataFrame from ``Client.get()``/``Client.get_local()`` with
318
+ ``layout = "long"`` metadata attached.
319
+ names_from: Column to spread into new column names. ``None``
320
+ (default) derives it from the dataset's ``measure_name_column``
321
+ metadata.
322
+ values_from: Column to fill the new wide columns with. ``None``
323
+ (default) derives it from ``value_columns`` metadata — only
324
+ when that list has exactly one entry present in `df`.
325
+ id_cols: Columns to keep as row keys. ``None`` (default) uses the
326
+ dataset's ``id_columns`` metadata intersected with `df`'s
327
+ columns, falling back to every other column.
328
+ values_fill: Value to fill missing cells with after pivoting
329
+ (forwarded to ``DataFrame.fillna`` on the pivoted result).
330
+ name: Dataset identifier, used only to fetch metadata when `df` has
331
+ none attached.
332
+ client: A :class:`Client` instance, used only with `name` to fetch
333
+ metadata when none is attached.
334
+
335
+ Returns:
336
+ A wide-format ``pd.DataFrame``.
337
+
338
+ Raises:
339
+ ReshapeError: no layout metadata, layout is ``feature``/``entity``,
340
+ a geometry column is present, layout is not ``long``,
341
+ ``names_from``/``values_from`` cannot be resolved unambiguously,
342
+ or a resolved column is missing from `df`. ``ValueError``
343
+ (raised by ``pandas.DataFrame.pivot``) propagates unchanged if
344
+ ``id_cols``/``names_from`` do not uniquely identify rows — this
345
+ is intentional: silently aggregating duplicates would hide a
346
+ real data problem.
347
+
348
+ Example:
349
+ >>> long = client.get("some_long_series_table")
350
+ >>> wide = pivot_wider(long)
351
+ """
352
+ meta = _get_eolas_meta(df, name=name, client=client)
353
+ layout = _reshape_guard(df, meta, name=name)
354
+ ds_name = _dataset_label(df, name)
355
+
356
+ if layout != "long":
357
+ hint = (
358
+ " This dataset is already wide — see pivot_longer() to go the " "other way."
359
+ if layout == "wide"
360
+ else ""
361
+ )
362
+ raise ReshapeError(
363
+ f"Cannot pivot_wider {ds_name!r}: layout is {layout!r}, not "
364
+ f"'long'.{hint}"
365
+ )
366
+
367
+ if names_from is None or values_from is None:
368
+ derived_names = names_from or meta.get("measure_name_column")
369
+ value_cols_meta = [
370
+ c for c in _as_list(meta.get("value_columns")) if c in df.columns
371
+ ]
372
+ derived_values = values_from or (
373
+ value_cols_meta[0] if len(value_cols_meta) == 1 else None
374
+ )
375
+ if not derived_names or not derived_values:
376
+ raise ReshapeError(
377
+ f"Cannot pivot_wider {ds_name!r}: names_from/values_from were "
378
+ "not supplied and cannot be derived unambiguously. Metadata "
379
+ f"has measure_name_column={meta.get('measure_name_column')!r} "
380
+ f"and value_columns={value_cols_meta!r}. Supply both "
381
+ "explicitly: pivot_wider(df, names_from=..., values_from=...)."
382
+ )
383
+ names_from = names_from or derived_names
384
+ values_from = values_from or derived_values
385
+
386
+ if names_from not in df.columns:
387
+ raise ReshapeError(
388
+ f"Cannot pivot_wider {ds_name!r}: names_from column {names_from!r} "
389
+ "not found in this DataFrame."
390
+ )
391
+ if values_from not in df.columns:
392
+ raise ReshapeError(
393
+ f"Cannot pivot_wider {ds_name!r}: values_from column "
394
+ f"{values_from!r} not found in this DataFrame."
395
+ )
396
+
397
+ if id_cols is None:
398
+ meta_id_cols = [c for c in _as_list(meta.get("id_columns")) if c in df.columns]
399
+ resolved_id_cols = [
400
+ c for c in meta_id_cols if c not in (names_from, values_from)
401
+ ]
402
+ if not resolved_id_cols:
403
+ resolved_id_cols = [
404
+ c for c in df.columns if c not in (names_from, values_from)
405
+ ]
406
+ else:
407
+ resolved_id_cols = list(id_cols)
408
+
409
+ wide = df.pivot(index=resolved_id_cols, columns=names_from, values=values_from)
410
+ wide = wide.reset_index()
411
+ wide.columns.name = None
412
+ if values_fill is not None:
413
+ wide = wide.fillna(values_fill)
414
+ # Result is now wide — re-declare it so pivot_longer() can reverse it. The new
415
+ # measure columns are everything that isn't a retained id column.
416
+ new_value_cols = [c for c in wide.columns if c not in resolved_id_cols]
417
+ return _attach_reshaped_meta(
418
+ wide,
419
+ df,
420
+ layout="wide",
421
+ time_columns=_as_list(meta.get("time_columns")),
422
+ id_columns=resolved_id_cols,
423
+ value_columns=new_value_cols,
424
+ measure_name_column="",
425
+ )
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "eolas-data"
7
- version = "1.10.0"
7
+ version = "1.11.0"
8
8
  description = "Python client for the eolas.fyi statistical data API (NZ + OECD; Australia on roadmap)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }