-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_checks.py
More file actions
1527 lines (1162 loc) · 40.2 KB
/
Copy path_checks.py
File metadata and controls
1527 lines (1162 loc) · 40.2 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import functools
import inspect
from collections.abc import Collection, Sequence
from typing import Any, Callable, Literal, Optional, get_args, get_type_hints
import narwhals.stable.v1 as nw
from narwhals.stable.v1.dependencies import (
get_cudf,
get_modin,
get_pandas,
get_polars,
get_pyarrow,
)
from .selectors import Selector
INF = float("inf")
NEG_INF = float("-inf")
def _is_polars_series(ser: Any) -> bool:
return (pl := get_polars()) is not None and issubclass(ser, pl.Series)
def _is_polars_expr(expr: Any) -> bool:
return (pl := get_polars()) is not None and issubclass(expr, pl.Expr)
def _is_polars_dataframe(df: Any) -> bool:
return (pl := get_polars()) is not None and issubclass(df, pl.DataFrame)
def _is_pandas_series(ser: Any) -> bool:
return (pd := get_pandas()) is not None and issubclass(ser, pd.Series)
def _is_pandas_dataframe(df: Any) -> bool:
return (pd := get_pandas()) is not None and issubclass(df, pd.DataFrame)
def _is_modin_dataframe(df: Any) -> bool:
return (mpd := get_modin()) is not None and issubclass(df, mpd.DataFrame)
def _is_modin_series(ser: Any) -> bool:
return (mpd := get_modin()) is not None and issubclass(ser, mpd.Series)
def _is_cudf_dataframe(df: Any) -> bool:
return (cudf := get_cudf()) is not None and issubclass(df, cudf.DataFrame)
def _is_cudf_series(ser: Any) -> bool:
return (cudf := get_cudf()) is not None and issubclass(ser, cudf.Series)
def _is_pyarrow_expr(expr: Any) -> bool:
return (pa := get_pyarrow()) is not None and issubclass(expr, pa.compute.Expression)
def _is_pyarrow_chunked_array(ser: Any) -> bool:
return (pa := get_pyarrow()) is not None and issubclass(ser, pa.ChunkedArray)
def _is_pyarrow_table(df: Any) -> bool:
return (pa := get_pyarrow()) is not None and issubclass(df, pa.Table)
def _is_series(x: Any) -> bool:
return (
issubclass(x, nw.Series)
or _is_pandas_series(x)
or _is_modin_series(x)
or _is_cudf_series(x)
or _is_polars_series(x)
or _is_pyarrow_chunked_array(x)
)
def _is_expr(x: Any) -> bool:
return issubclass(x, nw.Expr) or _is_polars_expr(x)
def _is_dataframe(x: Any) -> bool:
return (
issubclass(x, nw.DataFrame)
or _is_polars_dataframe(x)
or _is_pandas_dataframe(x)
or _is_modin_dataframe(x)
or _is_cudf_dataframe(x)
or _is_pyarrow_table(x)
)
def _infer_input_type(
type_hints: dict[str, Any], signature: inspect.Signature
) -> CheckInputType:
params = signature.parameters
if len(params) == 0:
return None
first_param_name = list(params.keys())[0]
try:
type_hint = type_hints[first_param_name]
except KeyError:
return "auto"
if issubclass(type_hint, str):
return "str"
elif _is_dataframe(type_hint):
return "Frame"
elif _is_series(type_hint):
return "Series"
return "auto"
def _infer_return_type(typ) -> CheckReturnType:
if issubclass(typ, bool):
return "bool"
elif _is_expr(typ):
return "Expr"
elif _is_series(typ):
return "Series"
return "auto"
def _infer_narwhals(type_hints: dict[str, Any]) -> bool | Literal["auto"]:
if len(type_hints) == 0:
return "auto"
return any(
issubclass(v, nw.Expr)
or issubclass(v, nw.Series)
or issubclass(v, nw.DataFrame)
for v in type_hints.values()
)
def _numeric_to_expr(expr: str | float | nw.Expr) -> nw.Expr:
if isinstance(expr, str):
return nw.col(expr)
elif isinstance(expr, nw.Expr):
return expr
else:
return nw.lit(expr)
def _get_repr(x: Any) -> str:
# Unfortunately the representation of an expression is not very good
if isinstance(x, nw.Expr):
return "Expr"
return f"{x}"
ClosedInterval = Literal["left", "right", "none", "both"]
def _is_not_null(name: str) -> nw.Expr:
return nw.col(name).is_null().__invert__()
def _is_not_nan(name: str) -> nw.Expr:
return nw.col(name).is_nan().__invert__()
def _is_not_inf(name: str) -> nw.Expr:
return nw.col(name).is_in((INF, NEG_INF)).__invert__()
def _is_between(
name: str,
lower_bound,
upper_bound,
closed: ClosedInterval,
) -> nw.Expr:
return nw.col(name).is_between(lower_bound, upper_bound, closed=closed)
def _lt(name: str, other) -> nw.Expr:
return nw.col(name) < other
def _le(name: str, other) -> nw.Expr:
return nw.col(name) <= other
def _gt(name: str, other) -> nw.Expr:
return nw.col(name) > other
def _ge(name: str, other) -> nw.Expr:
return nw.col(name) >= other
def _eq(name: str, other) -> nw.Expr:
return nw.col(name) == other
def _private_approx_eq(
left: nw.Expr,
right: nw.Expr,
rtol: float,
atol: float,
nan_equal: bool,
) -> nw.Expr:
res = (
left.__sub__(right)
.abs()
.__le__(nw.lit(atol).__add__(rtol).__mul__(right.abs()))
)
if nan_equal:
res = res.__or__(left.is_nan().__and__(right.is_nan()))
return res
def _approx_eq(name: str, other, rtol, atol, nan_equal) -> nw.Expr:
return _private_approx_eq(nw.col(name), other, rtol, atol, nan_equal)
def _series_lit_approx_eq(
left: nw.Series, right: float, rtol: float, atol: float, nan_equal: bool
) -> nw.Series:
name = "__checkedframe_approx_eq__"
return left.to_frame().select(
_private_approx_eq(
nw.col(left.name), nw.lit(right), rtol=rtol, atol=atol, nan_equal=nan_equal
).alias(name)
)[name]
def _is_in(name: str, other: Collection) -> nw.Expr:
return nw.col(name).is_in(other)
def _is_finite(name: str) -> nw.Expr:
return nw.col(name).is_finite()
def _is_sorted(s: nw.Series, descending: bool) -> bool:
return s.is_sorted(descending=descending)
def _is_id(df: nw.DataFrame, subset: str | list[str]) -> bool:
n_rows = df.shape[0]
# n_unique on dataframes is not available on narhwals, so if we have only one
# column specified as the subset, take a potential fast path, otherwise fallback to
# a generic version
if isinstance(subset, str):
n_unique_rows = df[subset].n_unique()
else:
n_unique_rows = df.select(subset).unique().shape[0]
return n_rows == n_unique_rows
def _series_equals(
left: nw.Series,
right: nw.Series,
check_dtypes: bool = True,
check_exact: bool = False,
rtol: float = 1e-5,
atol: float = 1e-8,
) -> bool:
if check_dtypes:
if left.dtype != right.dtype:
return False
if left.dtype.is_float() and not check_exact:
return (
left.to_frame()
.with_columns(right)
.select(
_private_approx_eq(
nw.col(left.name),
nw.col(right.name),
rtol=rtol,
atol=atol,
nan_equal=True,
).all()
)
.item()
)
else:
return (left == right).all()
def _frame_equals(
left: nw.DataFrame,
right: nw.DataFrame,
check_column_order: bool = True,
check_dtypes: bool = True,
check_exact: bool = False,
rtol: float = 1e-5,
atol: float = 1e-8,
) -> bool:
l_cols = left.columns
r_cols = right.columns
if check_column_order:
if l_cols != r_cols:
return False
else:
if set(l_cols) != set(r_cols):
return False
results = []
for c in l_cols:
results.append(
_series_equals(
left[c],
right[c],
check_dtypes=check_dtypes,
check_exact=check_exact,
rtol=rtol,
atol=atol,
)
)
return all(results)
def _frame_is_sorted(
df: nw.DataFrame,
by: str | Sequence[str],
descending: bool | Sequence[bool],
compare_all: bool,
) -> bool:
if compare_all:
df_sorted = df.sort(by=by, descending=descending)
return _frame_equals(df, df_sorted, check_exact=True)
else:
if isinstance(by, str):
assert isinstance(descending, bool)
return df[by].is_sorted(descending=descending)
else:
return _frame_equals(
df.select(by), df.select(by).sort(by=by, descending=descending)
)
def _str_ends_with(name: str, suffix: str) -> nw.Expr:
return nw.col(name).str.ends_with(suffix)
def _str_starts_with(name: str, prefix: str) -> nw.Expr:
return nw.col(name).str.starts_with(prefix)
def _str_contains(name: str, pattern: str, literal: bool = False) -> nw.Expr:
return nw.col(name).str.contains(pattern, literal=literal)
CardinalityRatio = Literal["1:1", "1:m", "m:1"]
def _cardinality_ratio(
df: nw.DataFrame,
left: str,
right: str,
cardinality: CardinalityRatio,
by: str | list[str] | None = None,
allow_duplicates: bool = False,
):
index_col = "__checkedframe_temp_cardinality_ratio_private_index__"
result_col = left
original_lf = df.with_row_index(index_col).lazy()
if by is None:
by = "__checkedframe_temp_cardinality_ratio_private_by__"
original_lf = original_lf.with_columns(nw.lit(1).alias(by))
if isinstance(by, str):
by = [by]
lf = original_lf.select(left, right, *by)
if allow_duplicates:
lf = lf.unique()
if cardinality == "1:1":
result_lf = (
lf.group_by(by)
.agg(
nw.col(left).n_unique().__eq__(nw.len()),
nw.col(right).n_unique().__eq__(nw.len()),
)
.select(*by, nw.col(left).__and__(nw.col(right)).alias(result_col))
)
elif cardinality == "1:m":
result_lf = (
lf.group_by(by)
.agg(nw.col(left).n_unique().__eq__(nw.len()).alias(result_col))
.select(*by, result_col)
)
elif cardinality == "m:1":
result_lf = (
lf.group_by(by)
.agg(nw.col(right).n_unique().__eq__(nw.len()).alias(result_col))
.select(*by, result_col)
)
else:
raise ValueError(
f"Invalid cardinality `{cardinality}`, must be one of `{get_args(CardinalityRatio)}`"
)
return (
original_lf.select(index_col, *by)
.join(result_lf, on=by, how="left")
.sort(index_col) # joins are not guaranteed to preserve order
.select(result_col)
.collect()[result_col]
)
CheckInputType = Optional[Literal["auto", "Frame", "str", "Series"]]
CheckReturnType = Literal["auto", "bool", "Expr", "Series"]
class Check:
"""Represents a check to run.
Parameters
----------
func : Optional[Callable], optional
The check to run, by default None
columns : Optional[str | list[str] | Selector], optional
The columns associated with the check, by default None
input_type : Optional[Literal["auto", "Frame", "str", "Series"]], optional
The input to the check function. If "auto", attempts to determine via the
context, by default "auto"
return_type : Literal["auto", "bool", "Expr", "Series"], optional
The return type of the check function. If "auto", attempts to determine via the
context, by default "auto"
native : bool | Literal["auto"], optional
Whether to run the check on the native DataFrame or the Narwhals DataFrame. If
"auto", attempts to determine via the context, by default "auto"
name : Optional[str], optional
The name of the check, by default None
description : Optional[str], optional
The description of the check. If None, attempts to read from the __doc__
attribute, by default None
"""
def __init__(
self,
func: Optional[Callable] = None,
columns: Optional[str | list[str] | Selector] = None,
input_type: CheckInputType = "auto",
return_type: CheckReturnType = "auto",
native: bool | Literal["auto"] = "auto",
name: Optional[str] = None,
description: Optional[str] = None,
):
self.func = func
self.input_type = input_type
self.return_type = return_type
self.native = native
self.name = name
self.description = description
self.columns = [columns] if isinstance(columns, str) else columns
if self.func is not None:
self._set_params()
def _set_params(self) -> None:
assert self.func is not None
auto_input_type = self.input_type == "auto"
auto_return_type = self.return_type == "auto"
auto_native = self.native == "auto"
if auto_input_type or auto_return_type or auto_native:
signature = inspect.signature(self.func)
type_hints = get_type_hints(self.func)
if auto_native:
self.native = not _infer_narwhals(type_hints)
if auto_input_type:
self.input_type = _infer_input_type(type_hints, signature)
if auto_return_type:
try:
self.return_type = _infer_return_type(
type_hints["return"],
)
except KeyError:
self.return_type = "auto"
if self.native == "auto":
raise ValueError(
f"Whether `{self.name}` expects to be run natively or via narwhals could not be automatically determined from context"
)
if self.input_type == "auto":
raise ValueError(
f"Input type of `{self.name}` could not be automatically determined from context"
)
if self.name is None:
self.name = None if self.func.__name__ == "<lambda>" else self.func.__name__
if self.description is None:
self.description = "" if self.func.__doc__ is None else self.func.__doc__
def __call__(self, func: Callable):
return Check(
func=func,
columns=self.columns,
input_type=self.input_type, # type: ignore
return_type=self.return_type, # type: ignore
native=self.native,
name=self.name,
description=self.description,
)
@staticmethod
def is_not_null() -> Check:
"""Tests whether values are not null.
.. note::
This method is mainly here for completeness. Columns are by default not
nullable.
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
customer_id = cf.String(checks=[cf.Check.is_not_null()])
df = pl.DataFrame({"customer_id": ["a23", None]})
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 2 error(s)
customer_id: 2 error(s)
- `nullable=False` failed for 1 / 2 (50.00%) rows: Must not be null
- is_not_null failed for 1 / 2 (50.00%) rows: Must not be null
"""
return Check(
func=_is_not_null,
input_type="str",
return_type="Expr",
native=False,
name="is_not_null",
description="Must not be null",
)
@staticmethod
def is_not_nan() -> Check:
"""Tests whether values are not NaN.
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
balances = cf.Float64(checks=[cf.Check.is_not_nan()])
df = pl.DataFrame({"balances": [1, 2, float("nan")]})
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 1 error(s)
balances: 1 error(s)
- is_not_nan failed for 1 / 3 (33.33%) rows: Must not be NaN
"""
return Check(
func=_is_not_nan,
input_type="str",
return_type="Expr",
native=False,
name="is_not_nan",
description="Must not be NaN",
)
@staticmethod
def is_not_inf() -> Check:
"""Tests whether values are not infinite.
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
balances = cf.Float64(checks=[cf.Check.is_not_inf()])
df = pl.DataFrame({"balances": [1, 2, float("inf")]})
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 1 error(s)
balances: 1 error(s)
- is_not_inf failed for 1 / 3 (33.33%) rows: Must not be inf/-inf
"""
return Check(
func=_is_not_inf,
input_type="str",
return_type="Expr",
native=False,
name="is_not_inf",
description="Must not be inf/-inf",
)
@staticmethod
def is_between(
lower_bound: Any, upper_bound: Any, closed: ClosedInterval = "both"
) -> Check:
"""Tests whether values are between `lower_bound` and `upper_bound`. Strings are
interpreted as column names.
Parameters
----------
lower_bound : Any
The lower bound
upper_bound : Any
The upper bound
closed : ClosedInterval, optional
Defines which sides of the interval are closed, by default "both"
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
age = cf.Int64(checks=[cf.Check.is_between(0, 128)])
min_balance = cf.Int64()
med_balance = cf.Int64(checks=[cf.Check.is_between("min_balance", "max_balance")])
max_balance = cf.Int64()
df = pl.DataFrame(
{
"age": [5, 10, 150],
"min_balance": [1, 100, 500],
"med_balance": [0, 83, 525],
"max_balance": [788, 82, 550],
}
)
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 2 error(s)
age: 1 error(s)
- is_between failed for 1 / 3 (33.33%) rows: Must be in range [0, 128]
med_balance: 1 error(s)
- is_between failed for 2 / 3 (66.67%) rows: Must be in range [min_balance, max_balance]
"""
if closed == "both":
l_paren, r_paren = ("[", "]")
elif closed == "left":
l_paren, r_paren = ("[", ")")
elif closed == "right":
l_paren, r_paren = ("(", "]")
elif closed == "none":
l_paren, r_paren = ("(", ")")
return Check(
func=functools.partial(
_is_between,
lower_bound=lower_bound,
upper_bound=upper_bound,
closed=closed,
),
input_type="str",
return_type="Expr",
native=False,
name="is_between",
description=f"Must be in range {l_paren}{lower_bound}, {upper_bound}{r_paren}",
)
@staticmethod
def lt(other: Any) -> Check:
"""Tests whether values are less than `other`. Strings are interpreted as
column names.
Parameters
----------
other : Any
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
age = cf.Int64(
checks=[
cf.Check.lt(10),
cf.Check.lt("max_age"),
cf.Check.lt(cf.col("max_age") - 10),
]
)
df = pl.DataFrame(
{
"age": [5, 10, 11],
"max_age": [10, 5, 8],
}
)
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 2 error(s)
age: 2 error(s)
- less_than failed for 2 / 3 (66.67%) rows: Must be < 10
- less_than failed for 1 / 3 (33.33%) rows: Must be < max_age
"""
return Check(
func=functools.partial(_lt, other=_numeric_to_expr(other)),
input_type="str",
return_type="Expr",
native=False,
name="less_than",
description=f"Must be < {_get_repr(other)}",
)
@staticmethod
def le(other: Any) -> Check:
"""Tests whether values are less than or equal to `other`. Strings are
interpreted as column names.
Parameters
----------
other : Any
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
age = cf.Int64(
checks=[
cf.Check.le(10),
cf.Check.le("max_age"),
cf.Check.le(cf.col("max_age") - 10),
]
)
df = pl.DataFrame(
{
"age": [5, 10, 11],
"max_age": [10, 5, 8],
}
)
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 1 error(s)
age: 1 error(s)
- less_than_or_equal_to failed for 1 / 3 (33.33%) rows: Must be <= 10
"""
return Check(
func=functools.partial(_le, other=_numeric_to_expr(other)),
input_type="str",
return_type="Expr",
native=False,
name="less_than_or_equal_to",
description=f"Must be <= {_get_repr(other)}",
)
@staticmethod
def gt(other: Any) -> Check:
"""Tests whether values are greater than `other`. Strings are interpreted as
column names.
Parameters
----------
other : Any
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
age = cf.Int64(
checks=[
cf.Check.gt(10),
cf.Check.gt("min_age"),
cf.Check.gt(cf.col("min_age") - 100),
]
)
df = pl.DataFrame(
{
"age": [5, 10, 11],
"min_age": [10, 5, 8],
}
)
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 2 error(s)
age: 2 error(s)
- greater_than failed for 2 / 3 (66.67%) rows: Must be > 10
- greater_than failed for 1 / 3 (33.33%) rows: Must be > min_age
"""
return Check(
func=functools.partial(_gt, other=_numeric_to_expr(other)),
input_type="str",
return_type="Expr",
native=False,
name="greater_than",
description=f"Must be > {_get_repr(other)}",
)
@staticmethod
def ge(other: Any) -> Check:
"""Tests whether values are greater than or equal to `other`. Strings are
interpreted as column names.
Parameters
----------
other : Any
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
age = cf.Int64(
checks=[
cf.Check.ge(10),
cf.Check.ge("min_age"),
cf.Check.ge(cf.col("min_age") - 10),
]
)
df = pl.DataFrame(
{
"age": [5, 10, 11],
"min_age": [10, 5, 8],
}
)
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 2 error(s)
age: 2 error(s)
- greater_than_or_equal_to failed for 1 / 3 (33.33%) rows: Must be >= 10
- greater_than_or_equal_to failed for 1 / 3 (33.33%) rows: Must be >= min_age
"""
return Check(
func=functools.partial(_ge, other=_numeric_to_expr(other)),
input_type="str",
return_type="Expr",
native=False,
name="greater_than_or_equal_to",
description=f"Must be >= {_get_repr(other)}",
)
@staticmethod
def eq(other: Any) -> Check:
"""Tests whether values are equal to `other`. Strings are interpreted as column
names.
Parameters
----------
other : Any
Returns
-------
Check
Examples
--------
.. code-block:: python
import checkedframe as cf
import polars as pl
class S(cf.Schema):
group = cf.String(checks=[cf.Check.eq("A")])
df = pl.DataFrame({"group": ["A", "B", "A"]})
S.validate(df)
Output:
.. code-block:: text
SchemaError: Found 1 error(s)
group: 1 error(s)
- equal_to failed for 1 / 3 (33.33%) rows: Must be = A
"""
return Check(
func=functools.partial(_eq, other=_numeric_to_expr(other)),
input_type="str",
return_type="Expr",
native=False,
name="equal_to",
description=f"Must be = {_get_repr(other)}",
)