pizzlies 0.2.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.
- pizzlies/__init__.py +255 -0
- pizzlies/_plugin/__init__.py +4 -0
- pizzlies/_plugin/_vendored.py +312 -0
- pizzlies/_plugin/dataframe.py +1608 -0
- pizzlies/_plugin/expr.py +485 -0
- pizzlies/_plugin/group_by.py +449 -0
- pizzlies/_plugin/lazy.py +795 -0
- pizzlies/_plugin/namespace.py +530 -0
- pizzlies/_plugin/parquet.py +1414 -0
- pizzlies/_plugin/repr.py +237 -0
- pizzlies/_plugin/schema.py +669 -0
- pizzlies/_plugin/selectors.py +41 -0
- pizzlies/_plugin/series.py +1560 -0
- pizzlies/_plugin/series_cat.py +22 -0
- pizzlies/_plugin/series_dt.py +246 -0
- pizzlies/_plugin/series_list.py +101 -0
- pizzlies/_plugin/series_str.py +211 -0
- pizzlies/_plugin/series_struct.py +29 -0
- pizzlies/_plugin/typing.py +25 -0
- pizzlies/_plugin/utils.py +1062 -0
- pizzlies/_plugin/window.py +62 -0
- pizzlies/py.typed +0 -0
- pizzlies/testing.py +46 -0
- pizzlies-0.2.0.dist-info/METADATA +210 -0
- pizzlies-0.2.0.dist-info/RECORD +28 -0
- pizzlies-0.2.0.dist-info/WHEEL +4 -0
- pizzlies-0.2.0.dist-info/entry_points.txt +3 -0
- pizzlies-0.2.0.dist-info/licenses/LICENSE +21 -0
pizzlies/__init__.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""A pure-Python, eager dataframe library whose native frame is a `dict[str, list]`.
|
|
2
|
+
|
|
3
|
+
Use it standalone, with Narwhals' API:
|
|
4
|
+
|
|
5
|
+
import pizzlies as pz
|
|
6
|
+
|
|
7
|
+
df = pz.from_dict({"a": [1, 2, 3]})
|
|
8
|
+
df.with_columns(b=pz.col("a") * 2)
|
|
9
|
+
|
|
10
|
+
or as a Narwhals plugin, where plain dicts become valid native frames:
|
|
11
|
+
|
|
12
|
+
import narwhals as nw
|
|
13
|
+
|
|
14
|
+
nw.from_native({"a": [1, 2, 3]}, eager_only=True)
|
|
15
|
+
|
|
16
|
+
Parquet files are read by a small pure-Python reader, which supports flat columns and the
|
|
17
|
+
common encodings and compression codecs (zstd needs Python 3.14+, or
|
|
18
|
+
`pip install 'pizzlies[zstd]'` before that).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import TYPE_CHECKING, Any
|
|
24
|
+
|
|
25
|
+
import narwhals as nw
|
|
26
|
+
from narwhals import (
|
|
27
|
+
Array,
|
|
28
|
+
Binary,
|
|
29
|
+
Boolean,
|
|
30
|
+
Categorical,
|
|
31
|
+
DataFrame,
|
|
32
|
+
Date,
|
|
33
|
+
Datetime,
|
|
34
|
+
Decimal,
|
|
35
|
+
Duration,
|
|
36
|
+
Enum,
|
|
37
|
+
Expr,
|
|
38
|
+
Field,
|
|
39
|
+
Float32,
|
|
40
|
+
Float64,
|
|
41
|
+
Int8,
|
|
42
|
+
Int16,
|
|
43
|
+
Int32,
|
|
44
|
+
Int64,
|
|
45
|
+
LazyFrame,
|
|
46
|
+
List,
|
|
47
|
+
Object,
|
|
48
|
+
Schema,
|
|
49
|
+
Series,
|
|
50
|
+
String,
|
|
51
|
+
Struct,
|
|
52
|
+
Time,
|
|
53
|
+
UInt8,
|
|
54
|
+
UInt16,
|
|
55
|
+
UInt32,
|
|
56
|
+
UInt64,
|
|
57
|
+
Unknown,
|
|
58
|
+
all,
|
|
59
|
+
all_horizontal,
|
|
60
|
+
any_horizontal,
|
|
61
|
+
coalesce,
|
|
62
|
+
col,
|
|
63
|
+
concat,
|
|
64
|
+
concat_str,
|
|
65
|
+
corr,
|
|
66
|
+
cov,
|
|
67
|
+
exceptions,
|
|
68
|
+
exclude,
|
|
69
|
+
format,
|
|
70
|
+
len,
|
|
71
|
+
lit,
|
|
72
|
+
max,
|
|
73
|
+
max_horizontal,
|
|
74
|
+
mean,
|
|
75
|
+
mean_horizontal,
|
|
76
|
+
median,
|
|
77
|
+
min,
|
|
78
|
+
min_horizontal,
|
|
79
|
+
nth,
|
|
80
|
+
selectors,
|
|
81
|
+
struct,
|
|
82
|
+
sum,
|
|
83
|
+
sum_horizontal,
|
|
84
|
+
when,
|
|
85
|
+
)
|
|
86
|
+
from narwhals.plugins import PluginName
|
|
87
|
+
from pizzlies._plugin.utils import is_native_frame
|
|
88
|
+
|
|
89
|
+
if TYPE_CHECKING:
|
|
90
|
+
from collections.abc import Mapping, Sequence
|
|
91
|
+
|
|
92
|
+
from typing_extensions import TypeIs
|
|
93
|
+
|
|
94
|
+
from narwhals.typing import FileSource, IntoDType, IntoSchema, _2DArray
|
|
95
|
+
from narwhals.utils import Version
|
|
96
|
+
from pizzlies._plugin.lazy import LazyPlan
|
|
97
|
+
from pizzlies._plugin.namespace import DictNamespace
|
|
98
|
+
from pizzlies._plugin.typing import DictFrame
|
|
99
|
+
|
|
100
|
+
__version__: str
|
|
101
|
+
|
|
102
|
+
BACKEND = PluginName("pizzlies")
|
|
103
|
+
"""This package's plugin name, for any Narwhals function which takes a `backend`."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def from_dict(
|
|
107
|
+
data: Mapping[str, Any],
|
|
108
|
+
schema: IntoSchema | Mapping[str, IntoDType | None] | None = None,
|
|
109
|
+
) -> DataFrame[Any]:
|
|
110
|
+
"""Instantiate a DataFrame from a dictionary of columns, see `narwhals.from_dict`."""
|
|
111
|
+
return nw.from_dict(data, schema, backend=BACKEND)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def from_dicts(
|
|
115
|
+
data: Sequence[Mapping[str, Any]],
|
|
116
|
+
schema: IntoSchema | Mapping[str, IntoDType | None] | None = None,
|
|
117
|
+
) -> DataFrame[Any]:
|
|
118
|
+
"""Instantiate a DataFrame from a sequence of rows, see `narwhals.from_dicts`."""
|
|
119
|
+
return nw.from_dicts(data, schema, backend=BACKEND)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def from_numpy(
|
|
123
|
+
data: _2DArray, schema: IntoSchema | Sequence[str] | None = None
|
|
124
|
+
) -> DataFrame[Any]:
|
|
125
|
+
"""Instantiate a DataFrame from a 2D NumPy array, see `narwhals.from_numpy`."""
|
|
126
|
+
return nw.from_numpy(data, schema, backend=BACKEND)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def from_arrow(native_frame: Any) -> DataFrame[Any]:
|
|
130
|
+
"""Instantiate a DataFrame from an Arrow table (anything with `__arrow_c_stream__`)."""
|
|
131
|
+
return nw.from_arrow(native_frame, backend=BACKEND)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def new_series(name: str, values: Any, dtype: IntoDType | None = None) -> Series[Any]:
|
|
135
|
+
"""Instantiate a Series from an iterable of values, see `narwhals.new_series`."""
|
|
136
|
+
return nw.new_series(name, values, dtype, backend=BACKEND)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def read_csv(
|
|
140
|
+
source: FileSource, *, separator: str = ",", **kwargs: Any
|
|
141
|
+
) -> DataFrame[Any]:
|
|
142
|
+
"""Read a CSV file into a DataFrame, see `narwhals.read_csv`."""
|
|
143
|
+
return nw.read_csv(source, backend=BACKEND, separator=separator, **kwargs)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def read_parquet(source: FileSource, **kwargs: Any) -> DataFrame[Any]:
|
|
147
|
+
"""Read a Parquet file into a DataFrame, see `narwhals.read_parquet`."""
|
|
148
|
+
return nw.read_parquet(source, backend=BACKEND, **kwargs)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def scan_parquet(source: FileSource, **kwargs: Any) -> LazyFrame[Any]:
|
|
152
|
+
"""Read a Parquet file into a LazyFrame, see `narwhals.scan_parquet`."""
|
|
153
|
+
return nw.scan_parquet(source, backend=BACKEND, **kwargs)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# --- Narwhals plugin hooks -----------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
NATIVE_PACKAGE = "builtins"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def __narwhals_namespace__(version: Version) -> DictNamespace: # noqa: N807
|
|
162
|
+
from pizzlies._plugin.namespace import DictNamespace
|
|
163
|
+
|
|
164
|
+
return DictNamespace(version=version)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def is_native(native_object: object) -> TypeIs[DictFrame | LazyPlan]:
|
|
168
|
+
from pizzlies._plugin.lazy import LazyPlan
|
|
169
|
+
|
|
170
|
+
return is_native_frame(native_object) or isinstance(native_object, LazyPlan)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
__all__ = [
|
|
174
|
+
"BACKEND",
|
|
175
|
+
"Array",
|
|
176
|
+
"Binary",
|
|
177
|
+
"Boolean",
|
|
178
|
+
"Categorical",
|
|
179
|
+
"DataFrame",
|
|
180
|
+
"Date",
|
|
181
|
+
"Datetime",
|
|
182
|
+
"Decimal",
|
|
183
|
+
"Duration",
|
|
184
|
+
"Enum",
|
|
185
|
+
"Expr",
|
|
186
|
+
"Field",
|
|
187
|
+
"Float32",
|
|
188
|
+
"Float64",
|
|
189
|
+
"Int8",
|
|
190
|
+
"Int16",
|
|
191
|
+
"Int32",
|
|
192
|
+
"Int64",
|
|
193
|
+
"LazyFrame",
|
|
194
|
+
"List",
|
|
195
|
+
"Object",
|
|
196
|
+
"Schema",
|
|
197
|
+
"Series",
|
|
198
|
+
"String",
|
|
199
|
+
"Struct",
|
|
200
|
+
"Time",
|
|
201
|
+
"UInt8",
|
|
202
|
+
"UInt16",
|
|
203
|
+
"UInt32",
|
|
204
|
+
"UInt64",
|
|
205
|
+
"Unknown",
|
|
206
|
+
"all",
|
|
207
|
+
"all_horizontal",
|
|
208
|
+
"any_horizontal",
|
|
209
|
+
"coalesce",
|
|
210
|
+
"col",
|
|
211
|
+
"concat",
|
|
212
|
+
"concat_str",
|
|
213
|
+
"corr",
|
|
214
|
+
"cov",
|
|
215
|
+
"exceptions",
|
|
216
|
+
"exclude",
|
|
217
|
+
"format",
|
|
218
|
+
"from_arrow",
|
|
219
|
+
"from_dict",
|
|
220
|
+
"from_dicts",
|
|
221
|
+
"from_numpy",
|
|
222
|
+
"len",
|
|
223
|
+
"lit",
|
|
224
|
+
"max",
|
|
225
|
+
"max_horizontal",
|
|
226
|
+
"mean",
|
|
227
|
+
"mean_horizontal",
|
|
228
|
+
"median",
|
|
229
|
+
"min",
|
|
230
|
+
"min_horizontal",
|
|
231
|
+
"new_series",
|
|
232
|
+
"nth",
|
|
233
|
+
"read_csv",
|
|
234
|
+
"read_parquet",
|
|
235
|
+
"scan_parquet",
|
|
236
|
+
"selectors",
|
|
237
|
+
"struct",
|
|
238
|
+
"sum",
|
|
239
|
+
"sum_horizontal",
|
|
240
|
+
"when",
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
if not TYPE_CHECKING:
|
|
245
|
+
|
|
246
|
+
def __getattr__(name: str) -> Any:
|
|
247
|
+
if name == "__version__":
|
|
248
|
+
global __version__ # noqa: PLW0603
|
|
249
|
+
|
|
250
|
+
from importlib import metadata
|
|
251
|
+
|
|
252
|
+
__version__ = metadata.version(__name__)
|
|
253
|
+
return __version__
|
|
254
|
+
msg = f"module {__name__!r} has no attribute {name!r}"
|
|
255
|
+
raise AttributeError(msg)
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Helpers vendored from Narwhals' private modules.
|
|
2
|
+
|
|
3
|
+
`pizzlies` only imports from Narwhals' public API, so anything it needs from
|
|
4
|
+
`narwhals._*` is copied here instead. Keep these in sync with upstream on a
|
|
5
|
+
best-effort basis, there is no requirement that they stay identical.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from itertools import chain
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Generic, Literal, NoReturn, TypeVar, cast
|
|
15
|
+
|
|
16
|
+
from narwhals.exceptions import DuplicateError
|
|
17
|
+
from narwhals.utils import Implementation
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Callable, Collection, Container, Iterable, Mapping
|
|
21
|
+
from typing import TypeAlias
|
|
22
|
+
|
|
23
|
+
from typing_extensions import TypeIs
|
|
24
|
+
|
|
25
|
+
from narwhals.typing import SizeUnit
|
|
26
|
+
from narwhals.utils import Version
|
|
27
|
+
|
|
28
|
+
_T = TypeVar("_T")
|
|
29
|
+
FrameT = TypeVar("FrameT")
|
|
30
|
+
SeriesT = TypeVar("SeriesT")
|
|
31
|
+
|
|
32
|
+
EvalNames: TypeAlias = "Callable[[FrameT], Sequence[str]]"
|
|
33
|
+
EvalSeries: TypeAlias = "Callable[[FrameT], Sequence[SeriesT]]"
|
|
34
|
+
AliasNames: TypeAlias = "Callable[[Sequence[str]], Sequence[str]]"
|
|
35
|
+
NarwhalsAggregation: TypeAlias = Literal[
|
|
36
|
+
"sum",
|
|
37
|
+
"mean",
|
|
38
|
+
"median",
|
|
39
|
+
"max",
|
|
40
|
+
"min",
|
|
41
|
+
"mode",
|
|
42
|
+
"std",
|
|
43
|
+
"var",
|
|
44
|
+
"len",
|
|
45
|
+
"n_unique",
|
|
46
|
+
"count",
|
|
47
|
+
"quantile",
|
|
48
|
+
"all",
|
|
49
|
+
"any",
|
|
50
|
+
"first",
|
|
51
|
+
"last",
|
|
52
|
+
"any_value",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def assert_never(arg: Any, /) -> NoReturn: # pragma: no cover
|
|
57
|
+
msg = f"Expected code to be unreachable, but got: {arg!r}"
|
|
58
|
+
raise AssertionError(msg)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# --- `narwhals._utils` ---------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class not_implemented: # noqa: N801
|
|
65
|
+
"""Mark some functionality as unsupported, raising `NotImplementedError` on access."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, alias: str | None = None, /, *, hint: str = "") -> None:
|
|
68
|
+
self._alias: str | None = alias
|
|
69
|
+
self._hint: str = hint
|
|
70
|
+
|
|
71
|
+
def __repr__(self) -> str:
|
|
72
|
+
return f"<{type(self).__name__}>: {self._name_owner}.{self._name}"
|
|
73
|
+
|
|
74
|
+
def __set_name__(self, owner: type[Any], name: str) -> None:
|
|
75
|
+
self._name_owner: str = owner.__name__
|
|
76
|
+
self._name: str = self._alias or name
|
|
77
|
+
|
|
78
|
+
def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> Any:
|
|
79
|
+
if instance is None:
|
|
80
|
+
return self
|
|
81
|
+
implementation = getattr(instance, "_implementation", Implementation.UNKNOWN)
|
|
82
|
+
who = (
|
|
83
|
+
repr(implementation)
|
|
84
|
+
if implementation is not Implementation.UNKNOWN
|
|
85
|
+
else self._name_owner
|
|
86
|
+
)
|
|
87
|
+
fallback_msg = (
|
|
88
|
+
"If you would like to see this functionality in `narwhals`, "
|
|
89
|
+
"please open an issue at: https://github.com/narwhals-dev/narwhals/issues"
|
|
90
|
+
)
|
|
91
|
+
msg = f"{self._name!r} is not implemented for: {who!r}.\n\n{self._hint or fallback_msg}"
|
|
92
|
+
raise NotImplementedError(msg)
|
|
93
|
+
|
|
94
|
+
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
95
|
+
return self.__get__("raise")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def check_column_names_are_unique(columns: Collection[str]) -> None:
|
|
99
|
+
if len(columns) != len(set(columns)):
|
|
100
|
+
from collections import Counter
|
|
101
|
+
|
|
102
|
+
counter = Counter(columns)
|
|
103
|
+
duplicates = {k: v for k, v in counter.items() if v > 1}
|
|
104
|
+
msg = "".join(f"\n- '{k}' {v} times" for k, v in duplicates.items())
|
|
105
|
+
msg = f"Expected unique column names, got:{msg}"
|
|
106
|
+
raise DuplicateError(msg)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def is_sequence_of(obj: Any, tp: type[_T]) -> TypeIs[Sequence[_T]]:
|
|
110
|
+
# Only sniffs the first element.
|
|
111
|
+
return bool(
|
|
112
|
+
isinstance(obj, Sequence)
|
|
113
|
+
and not isinstance(obj, str)
|
|
114
|
+
and (first := next(iter(obj), None))
|
|
115
|
+
and isinstance(first, tp)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def isinstance_or_issubclass(obj_or_cls: Any, cls_or_tuple: Any) -> bool:
|
|
120
|
+
from narwhals.dtypes import DType
|
|
121
|
+
|
|
122
|
+
if isinstance(obj_or_cls, DType):
|
|
123
|
+
return isinstance(obj_or_cls, cls_or_tuple)
|
|
124
|
+
return isinstance(obj_or_cls, cls_or_tuple) or (
|
|
125
|
+
isinstance(obj_or_cls, type) and issubclass(obj_or_cls, cls_or_tuple)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def scale_bytes(sz: int, unit: SizeUnit) -> int | float:
|
|
130
|
+
if unit in {"b", "bytes"}:
|
|
131
|
+
return sz
|
|
132
|
+
if unit in {"kb", "kilobytes"}:
|
|
133
|
+
return sz / 1024
|
|
134
|
+
if unit in {"mb", "megabytes"}:
|
|
135
|
+
return sz / 1024**2
|
|
136
|
+
if unit in {"gb", "gigabytes"}:
|
|
137
|
+
return sz / 1024**3
|
|
138
|
+
if unit in {"tb", "terabytes"}:
|
|
139
|
+
return sz / 1024**4
|
|
140
|
+
msg = f"`unit` must be one of {{'b', 'kb', 'mb', 'gb', 'tb'}}, got {unit!r}"
|
|
141
|
+
raise ValueError(msg)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# --- `narwhals._expression_parsing` --------------------------------------------------
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def combine_evaluate_output_names(*exprs: Any) -> EvalNames[Any]:
|
|
148
|
+
# Follow left-hand-rule for naming. E.g. `nw.sum_horizontal(expr1, expr2)` takes the
|
|
149
|
+
# first name of `expr1`.
|
|
150
|
+
def evaluate_output_names(df: Any) -> Sequence[str]:
|
|
151
|
+
return exprs[0]._evaluate_output_names(df)[:1]
|
|
152
|
+
|
|
153
|
+
return evaluate_output_names
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def combine_alias_output_names(*exprs: Any) -> AliasNames | None:
|
|
157
|
+
if exprs[0]._alias_output_names is None:
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
def alias_output_names(names: Sequence[str]) -> Sequence[str]:
|
|
161
|
+
return exprs[0]._alias_output_names(names)[:1]
|
|
162
|
+
|
|
163
|
+
return alias_output_names
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def evaluate_output_names_and_aliases(
|
|
167
|
+
expr: Any, df: Any, exclude: Sequence[str]
|
|
168
|
+
) -> tuple[Sequence[str], Sequence[str]]:
|
|
169
|
+
output_names: Sequence[str] = expr._evaluate_output_names(df)
|
|
170
|
+
aliases: Sequence[str] = (
|
|
171
|
+
alias_fn(output_names)
|
|
172
|
+
if (alias_fn := expr._alias_output_names) is not None
|
|
173
|
+
else output_names
|
|
174
|
+
)
|
|
175
|
+
if exclude and expr._metadata.expansion_kind.is_multi_unnamed():
|
|
176
|
+
exclude_set = frozenset(exclude)
|
|
177
|
+
# Not `zip(*...)`: excluding every column must give no names, not an error.
|
|
178
|
+
kept = [
|
|
179
|
+
(x, alias)
|
|
180
|
+
for x, alias in zip(output_names, aliases, strict=True)
|
|
181
|
+
if x not in exclude_set
|
|
182
|
+
]
|
|
183
|
+
output_names = [x for x, _ in kept]
|
|
184
|
+
aliases = [alias for _, alias in kept]
|
|
185
|
+
return output_names, aliases
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def evaluate_aliases(frame: Any, exprs: Iterable[Any], /) -> list[str]:
|
|
189
|
+
return list(chain.from_iterable(expr._evaluate_aliases(frame) for expr in exprs))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# --- `narwhals._compliant` -----------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class SeriesNamespace(Generic[SeriesT]):
|
|
196
|
+
"""Base for `Series.<accessor>` namespaces, wrapping a compliant series."""
|
|
197
|
+
|
|
198
|
+
def __init__(self, series: SeriesT, /) -> None:
|
|
199
|
+
self._compliant_series = series
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def compliant(self) -> SeriesT:
|
|
203
|
+
return self._compliant_series
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def implementation(self) -> Implementation:
|
|
207
|
+
return self._compliant_series._implementation # type: ignore[attr-defined]
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def backend_version(self) -> tuple[int, ...]:
|
|
211
|
+
return self.implementation._backend_version()
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def native(self) -> Any:
|
|
215
|
+
return self._compliant_series.native # type: ignore[attr-defined]
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def version(self) -> Version:
|
|
219
|
+
return self._compliant_series._version # type: ignore[attr-defined]
|
|
220
|
+
|
|
221
|
+
def with_native(self, series: Any, /) -> SeriesT:
|
|
222
|
+
return self._compliant_series._with_native(series) # type: ignore[attr-defined]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# --- `narwhals._duration` ------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
IntervalUnit: TypeAlias = Literal["ns", "us", "ms", "s", "m", "h", "d", "mo", "q", "y"]
|
|
228
|
+
_PATTERN_INTERVAL: re.Pattern[str] = re.compile(
|
|
229
|
+
r"^(?P<multiple>-?\d+)(?P<unit>ns|us|ms|mo|m|s|h|d|q|y)\Z"
|
|
230
|
+
)
|
|
231
|
+
_MONTH_MULTIPLES = frozenset([1, 2, 3, 4, 6, 12])
|
|
232
|
+
_QUARTER_MULTIPLES = frozenset([1, 2, 4])
|
|
233
|
+
_UNIT_TO_TIMEDELTA: Mapping[IntervalUnit, str] = {
|
|
234
|
+
"d": "days",
|
|
235
|
+
"h": "hours",
|
|
236
|
+
"m": "minutes",
|
|
237
|
+
"s": "seconds",
|
|
238
|
+
"ms": "milliseconds",
|
|
239
|
+
"us": "microseconds",
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class Interval:
|
|
244
|
+
def __init__(self, multiple: int, unit: IntervalUnit, /) -> None:
|
|
245
|
+
self.multiple: int = multiple
|
|
246
|
+
self.unit: IntervalUnit = unit
|
|
247
|
+
|
|
248
|
+
def to_timedelta(
|
|
249
|
+
self, *, unsupported: Container[IntervalUnit] = frozenset(("ns", "mo", "q", "y"))
|
|
250
|
+
) -> dt.timedelta:
|
|
251
|
+
if self.unit in unsupported: # pragma: no cover
|
|
252
|
+
msg = f"Creating timedelta with {self.unit} unit is not supported."
|
|
253
|
+
raise NotImplementedError(msg)
|
|
254
|
+
kwd = _UNIT_TO_TIMEDELTA[self.unit]
|
|
255
|
+
return dt.timedelta(**{kwd: self.multiple})
|
|
256
|
+
|
|
257
|
+
@classmethod
|
|
258
|
+
def parse(cls, every: str) -> Interval:
|
|
259
|
+
multiple, unit = cls._parse(every)
|
|
260
|
+
if unit == "mo" and multiple not in _MONTH_MULTIPLES:
|
|
261
|
+
msg = f"Only the following multiples are supported for 'mo' unit: {_MONTH_MULTIPLES}.\nGot: {multiple}."
|
|
262
|
+
raise ValueError(msg)
|
|
263
|
+
if unit == "q" and multiple not in _QUARTER_MULTIPLES:
|
|
264
|
+
msg = f"Only the following multiples are supported for 'q' unit: {_QUARTER_MULTIPLES}.\nGot: {multiple}."
|
|
265
|
+
raise ValueError(msg)
|
|
266
|
+
if unit == "y" and multiple != 1:
|
|
267
|
+
msg = (
|
|
268
|
+
f"Only multiple 1 is currently supported for 'y' unit.\nGot: {multiple}."
|
|
269
|
+
)
|
|
270
|
+
raise ValueError(msg)
|
|
271
|
+
return cls(multiple, unit)
|
|
272
|
+
|
|
273
|
+
@classmethod
|
|
274
|
+
def parse_no_constraints(cls, every: str) -> Interval:
|
|
275
|
+
return cls(*cls._parse(every))
|
|
276
|
+
|
|
277
|
+
@staticmethod
|
|
278
|
+
def _parse(every: str) -> tuple[int, IntervalUnit]:
|
|
279
|
+
from typing import get_args
|
|
280
|
+
|
|
281
|
+
if match := _PATTERN_INTERVAL.match(every):
|
|
282
|
+
return int(match["multiple"]), cast("IntervalUnit", match["unit"])
|
|
283
|
+
msg = (
|
|
284
|
+
f"Invalid `every` string: {every}. Expected string of kind <number><unit>, "
|
|
285
|
+
f"where 'unit' is one of: {get_args(IntervalUnit)}."
|
|
286
|
+
)
|
|
287
|
+
raise ValueError(msg)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# --- `narwhals._arrow.utils` (format inference for `str.to_datetime`) ---------------
|
|
291
|
+
|
|
292
|
+
DATE_RE = r"(?P<date>\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4}|\d{8})"
|
|
293
|
+
SEP_RE = r"(?P<sep>\s|T)"
|
|
294
|
+
TIME_RE = r"(?P<time>\d{2}:\d{2}(?::\d{2})?|\d{6}?)"
|
|
295
|
+
HMS_RE = r"^(?P<hms>\d{2}:\d{2}:\d{2})$"
|
|
296
|
+
HM_RE = r"^(?P<hm>\d{2}:\d{2})$"
|
|
297
|
+
HMS_RE_NO_SEP = r"^(?P<hms_no_sep>\d{6})$"
|
|
298
|
+
TZ_RE = r"(?P<tz>Z|[+-]\d{2}:?\d{2})" # 'Z', '+02:00', '+0200'
|
|
299
|
+
FULL_RE = rf"{DATE_RE}{SEP_RE}?{TIME_RE}?{TZ_RE}?$"
|
|
300
|
+
|
|
301
|
+
YMD_RE = r"^(?P<year>(?:[12][0-9])?[0-9]{2})(?P<sep1>[-/.])(?P<month>0[1-9]|1[0-2])(?P<sep2>[-/.])(?P<day>0[1-9]|[12][0-9]|3[01])$"
|
|
302
|
+
DMY_RE = r"^(?P<day>0[1-9]|[12][0-9]|3[01])(?P<sep1>[-/.])(?P<month>0[1-9]|1[0-2])(?P<sep2>[-/.])(?P<year>(?:[12][0-9])?[0-9]{2})$"
|
|
303
|
+
MDY_RE = r"^(?P<month>0[1-9]|1[0-2])(?P<sep1>[-/.])(?P<day>0[1-9]|[12][0-9]|3[01])(?P<sep2>[-/.])(?P<year>(?:[12][0-9])?[0-9]{2})$"
|
|
304
|
+
YMD_RE_NO_SEP = r"^(?P<year>(?:[12][0-9])?[0-9]{2})(?P<month>0[1-9]|1[0-2])(?P<day>0[1-9]|[12][0-9]|3[01])$"
|
|
305
|
+
|
|
306
|
+
DATE_FORMATS = (
|
|
307
|
+
(YMD_RE_NO_SEP, "%Y%m%d"),
|
|
308
|
+
(YMD_RE, "%Y-%m-%d"),
|
|
309
|
+
(DMY_RE, "%d-%m-%Y"),
|
|
310
|
+
(MDY_RE, "%m-%d-%Y"),
|
|
311
|
+
)
|
|
312
|
+
TIME_FORMATS = ((HMS_RE, "%H:%M:%S"), (HM_RE, "%H:%M"), (HMS_RE_NO_SEP, "%H%M%S"))
|