/
series.py
7811 lines (6721 loc) · 223 KB
/
series.py
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 contextlib
import math
from datetime import date, datetime, time, timedelta
from decimal import Decimal as PyDecimal
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Collection,
Generator,
Iterable,
Literal,
Mapping,
NoReturn,
Sequence,
Union,
overload,
)
import polars._reexport as pl
from polars import functions as F
from polars._utils.construction import (
arrow_to_pyseries,
dataframe_to_pyseries,
iterable_to_pyseries,
numpy_to_idxs,
numpy_to_pyseries,
pandas_to_pyseries,
sequence_to_pyseries,
series_to_pyseries,
)
from polars._utils.convert import (
date_to_int,
datetime_to_int,
time_to_int,
timedelta_to_int,
)
from polars._utils.deprecation import (
deprecate_function,
deprecate_nonkeyword_arguments,
deprecate_renamed_function,
deprecate_renamed_parameter,
issue_deprecation_warning,
)
from polars._utils.unstable import unstable
from polars._utils.various import (
BUILDING_SPHINX_DOCS,
_is_generator,
no_default,
parse_version,
range_to_slice,
scale_bytes,
sphinx_accessor,
warn_null_comparison,
)
from polars._utils.wrap import wrap_df
from polars.datatypes import (
Array,
Boolean,
Categorical,
Date,
Datetime,
Decimal,
Duration,
Enum,
Float64,
Int8,
Int16,
Int32,
Int64,
List,
Null,
Object,
String,
Time,
UInt8,
UInt32,
UInt64,
Unknown,
dtype_to_ctype,
is_polars_dtype,
maybe_cast,
numpy_char_code_to_dtype,
py_type_to_dtype,
supported_numpy_char_code,
)
from polars.dependencies import (
_HVPLOT_AVAILABLE,
_PYARROW_AVAILABLE,
_check_for_numpy,
_check_for_pandas,
_check_for_pyarrow,
hvplot,
)
from polars.dependencies import numpy as np
from polars.dependencies import pandas as pd
from polars.dependencies import pyarrow as pa
from polars.exceptions import ModuleUpgradeRequired, ShapeError
from polars.meta import get_index_type
from polars.series.array import ArrayNameSpace
from polars.series.binary import BinaryNameSpace
from polars.series.categorical import CatNameSpace
from polars.series.datetime import DateTimeNameSpace
from polars.series.list import ListNameSpace
from polars.series.string import StringNameSpace
from polars.series.struct import StructNameSpace
from polars.series.utils import expr_dispatch, get_ffi_func
from polars.slice import PolarsSlice
with contextlib.suppress(ImportError): # Module not available when building docs
from polars.polars import PyDataFrame, PySeries
if TYPE_CHECKING:
import sys
from hvplot.plotting.core import hvPlotTabularPolars
from polars import DataFrame, DataType, Expr
from polars._utils.various import (
NoDefault,
)
from polars.series._numpy import SeriesView
from polars.type_aliases import (
BufferInfo,
ClosedInterval,
ComparisonOperator,
FillNullStrategy,
InterpolationMethod,
IntoExpr,
IntoExprColumn,
NullBehavior,
NumericLiteral,
OneOrMoreDataTypes,
PolarsDataType,
PythonLiteral,
RankMethod,
RollingInterpolationMethod,
SearchSortedSide,
SeriesBuffers,
SizeUnit,
TemporalLiteral,
)
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
elif BUILDING_SPHINX_DOCS:
property = sphinx_accessor
ArrayLike = Union[
Sequence[Any],
"Series",
"pa.Array",
"pa.ChunkedArray",
"np.ndarray[Any, Any]",
"pd.Series[Any]",
"pd.DatetimeIndex",
]
@expr_dispatch
class Series:
"""
A Series represents a single column in a polars DataFrame.
Parameters
----------
name : str, default None
Name of the Series. Will be used as a column name when used in a DataFrame.
When not specified, name is set to an empty string.
values : ArrayLike, default None
One-dimensional data in various forms. Supported are: Sequence, Series,
pyarrow Array, and numpy ndarray.
dtype : DataType, default None
Data type of the resulting Series. If set to `None` (default), the data type is
inferred from the `values` input. The strategy for data type inference depends
on the `strict` parameter:
- If `strict` is set to True (default), the inferred data type is equal to the
first non-null value, or `Null` if all values are null.
- If `strict` is set to False, the inferred data type is the supertype of the
values, or :class:`Object` if no supertype can be found. **WARNING**: A full
pass over the values is required to determine the supertype.
- If no values were passed, the resulting data type is :class:`Null`.
strict : bool, default True
Throw an error if any value does not exactly match the given or inferred data
type. If set to `False`, values that do not match the data type are cast to
that data type or, if casting is not possible, set to null instead.
nan_to_null : bool, default False
In case a numpy array is used to create this Series, indicate how to deal
with np.nan values. (This parameter is a no-op on non-numpy data).
dtype_if_empty : DataType, default Null
Data type of the Series if `values` contains no non-null data.
.. deprecated:: 0.20.6
The data type for empty Series will always be `Null`, unless `dtype` is
specified. To preserve behavior, check if the resulting Series has data type
`Null` and cast to the desired data type.
This parameter will be removed in the next breaking release.
Examples
--------
Constructing a Series by specifying name and values positionally:
>>> s = pl.Series("a", [1, 2, 3])
>>> s
shape: (3,)
Series: 'a' [i64]
[
1
2
3
]
Notice that the dtype is automatically inferred as a polars Int64:
>>> s.dtype
Int64
Constructing a Series with a specific dtype:
>>> s2 = pl.Series("a", [1, 2, 3], dtype=pl.Float32)
>>> s2
shape: (3,)
Series: 'a' [f32]
[
1.0
2.0
3.0
]
It is possible to construct a Series with values as the first positional argument.
This syntax considered an anti-pattern, but it can be useful in certain
scenarios. You must specify any other arguments through keywords.
>>> s3 = pl.Series([1, 2, 3])
>>> s3
shape: (3,)
Series: '' [i64]
[
1
2
3
]
"""
_s: PySeries = None
_accessors: ClassVar[set[str]] = {
"arr",
"cat",
"dt",
"list",
"str",
"bin",
"struct",
"plot",
}
def __init__(
self,
name: str | ArrayLike | None = None,
values: ArrayLike | None = None,
dtype: PolarsDataType | None = None,
*,
strict: bool = True,
nan_to_null: bool = False,
dtype_if_empty: PolarsDataType = Null,
):
if dtype_if_empty != Null:
issue_deprecation_warning(
"The `dtype_if_empty` parameter for the Series constructor is deprecated."
" The data type for empty Series will always be Null, unless `dtype` is specified."
" To preserve behavior, check if the resulting Series has data type Null and cast to the desired data type."
" This parameter will be removed in the next breaking release.",
version="0.20.6",
)
# If 'Unknown' treat as None to trigger type inference
if dtype == Unknown:
dtype = None
elif dtype is not None and not is_polars_dtype(dtype):
# Raise early error on invalid dtype
if not is_polars_dtype(
pl_dtype := py_type_to_dtype(dtype, raise_unmatched=False)
):
msg = f"given dtype: {dtype!r} is not a valid Polars data type and cannot be converted into one"
raise ValueError(msg)
else:
dtype = pl_dtype
# Handle case where values are passed as the first argument
original_name: str | None = None
if name is None:
name = ""
elif isinstance(name, str):
original_name = name
else:
if values is None:
values = name
name = ""
else:
msg = "Series name must be a string"
raise TypeError(msg)
if isinstance(values, Sequence):
self._s = sequence_to_pyseries(
name,
values,
dtype=dtype,
strict=strict,
nan_to_null=nan_to_null,
)
elif values is None:
self._s = sequence_to_pyseries(name, [], dtype=dtype)
elif _check_for_numpy(values) and isinstance(values, np.ndarray):
self._s = numpy_to_pyseries(
name, values, strict=strict, nan_to_null=nan_to_null
)
if values.dtype.type in [np.datetime64, np.timedelta64]:
# cast to appropriate dtype, handling NaT values
dtype = _resolve_temporal_dtype(dtype, values.dtype)
if dtype is not None:
self._s = (
self.cast(dtype)
.scatter(np.argwhere(np.isnat(values)).flatten(), None)
._s
)
return
if dtype is not None:
self._s = self.cast(dtype, strict=True)._s
elif _check_for_pyarrow(values) and isinstance(
values, (pa.Array, pa.ChunkedArray)
):
self._s = arrow_to_pyseries(name, values)
elif _check_for_pandas(values) and isinstance(
values, (pd.Series, pd.Index, pd.DatetimeIndex)
):
self._s = pandas_to_pyseries(name, values)
elif _is_generator(values):
self._s = iterable_to_pyseries(name, values, dtype=dtype, strict=strict)
elif isinstance(values, Series):
self._s = series_to_pyseries(
original_name, values, dtype=dtype, strict=strict
)
elif isinstance(values, pl.DataFrame):
self._s = dataframe_to_pyseries(
original_name, values, dtype=dtype, strict=strict
)
else:
msg = (
f"Series constructor called with unsupported type {type(values).__name__!r}"
" for the `values` parameter"
)
raise TypeError(msg)
# Implementation of deprecated `dtype_if_empty` functionality
if dtype_if_empty != Null and self.dtype == Null:
self._s = self._s.cast(dtype_if_empty, False)
@classmethod
def _from_pyseries(cls, pyseries: PySeries) -> Self:
series = cls.__new__(cls)
series._s = pyseries
return series
@classmethod
def _import_from_c(cls, name: str, pointers: list[tuple[int, int]]) -> Self:
"""
Construct a Series from Arrows C interface.
Warning
-------
This will read the `array` pointer without moving it. The host process should
garbage collect the heap pointer, but not its contents.
"""
return cls._from_pyseries(PySeries._import_from_c(name, pointers))
def _get_buffer_info(self) -> BufferInfo:
"""
Return pointer, offset, and length information about the underlying buffer.
Returns
-------
tuple of ints
Tuple of the form (pointer, offset, length)
Raises
------
TypeError
If the `Series` data type is not physical.
ComputeError
If the `Series` contains multiple chunks.
Notes
-----
This method is mainly intended for use with the dataframe interchange protocol.
"""
return self._s._get_buffer_info()
def _get_buffers(self) -> SeriesBuffers:
"""
Return the underlying values, validity, and offsets buffers as Series.
The values buffer always exists.
The validity buffer may not exist if the column contains no null values.
The offsets buffer only exists for Series of data type `String` and `List`.
Returns
-------
dict
Dictionary with `"values"`, `"validity"`, and `"offsets"` keys mapping
to the corresponding buffer or `None` if the buffer doesn't exist.
Warnings
--------
The underlying buffers for `String` Series cannot be represented in this
format. Instead, the buffers are converted to a values and offsets buffer.
Notes
-----
This method is mainly intended for use with the dataframe interchange protocol.
"""
buffers = self._s._get_buffers()
keys = ("values", "validity", "offsets")
return { # type: ignore[return-value]
k: self._from_pyseries(b) if b is not None else b
for k, b in zip(keys, buffers)
}
@classmethod
def _from_buffer(
self, dtype: PolarsDataType, buffer_info: BufferInfo, owner: Any
) -> Self:
"""
Construct a Series from information about its underlying buffer.
Parameters
----------
dtype
The data type of the buffer.
Must be a physical type (integer, float, or boolean).
buffer_info
Tuple containing buffer information in the form `(pointer, offset, length)`.
owner
The object owning the buffer.
Returns
-------
Series
Raises
------
TypeError
When the given `dtype` is not supported.
Notes
-----
This method is mainly intended for use with the dataframe interchange protocol.
"""
return self._from_pyseries(PySeries._from_buffer(dtype, buffer_info, owner))
@classmethod
def _from_buffers(
self,
dtype: PolarsDataType,
data: Series | Sequence[Series],
validity: Series | None = None,
) -> Self:
"""
Construct a Series from information about its underlying buffers.
Parameters
----------
dtype
The data type of the resulting Series.
data
Buffers describing the data. For most data types, this is a single Series of
the physical data type of `dtype`. Some data types require multiple buffers:
- `String`: A data buffer of type `UInt8` and an offsets buffer
of type `Int64`. Note that this does not match how the data
is represented internally and data copy is required to construct
the Series.
validity
Validity buffer. If specified, must be a Series of data type `Boolean`.
Returns
-------
Series
Raises
------
TypeError
When the given `dtype` is not supported or the other inputs do not match
the requirements for constructing a Series of the given `dtype`.
Warnings
--------
Constructing a `String` Series requires specifying a values and offsets buffer,
which does not match the actual underlying buffers. The values and offsets
buffer are converted into the actual buffers, which copies data.
Notes
-----
This method is mainly intended for use with the dataframe interchange protocol.
"""
if isinstance(data, Series):
data = [data._s]
else:
data = [s._s for s in data]
if validity is not None:
validity = validity._s
return self._from_pyseries(PySeries._from_buffers(dtype, data, validity))
@property
def dtype(self) -> DataType:
"""
Get the data type of this Series.
Examples
--------
>>> s = pl.Series("a", [1, 2, 3])
>>> s.dtype
Int64
"""
return self._s.dtype()
@property
def flags(self) -> dict[str, bool]:
"""
Get flags that are set on the Series.
Returns
-------
dict
Dictionary containing the flag name and the value
"""
out = {
"SORTED_ASC": self._s.is_sorted_ascending_flag(),
"SORTED_DESC": self._s.is_sorted_descending_flag(),
}
if self.dtype == List:
out["FAST_EXPLODE"] = self._s.can_fast_explode_flag()
return out
@property
def inner_dtype(self) -> DataType | None:
"""
Get the inner dtype in of a List typed Series.
.. deprecated:: 0.19.14
Use `Series.dtype.inner` instead.
Returns
-------
DataType
"""
issue_deprecation_warning(
"`Series.inner_dtype` is deprecated. Use `Series.dtype.inner` instead.",
version="0.19.14",
)
try:
return self.dtype.inner # type: ignore[attr-defined]
except AttributeError:
return None
@property
def name(self) -> str:
"""
Get the name of this Series.
Examples
--------
>>> s = pl.Series("a", [1, 2, 3])
>>> s.name
'a'
"""
return self._s.name()
@property
def shape(self) -> tuple[int]:
"""
Shape of this Series.
Examples
--------
>>> s = pl.Series("a", [1, 2, 3])
>>> s.shape
(3,)
"""
return (self._s.len(),)
def __bool__(self) -> NoReturn:
msg = (
"the truth value of a Series is ambiguous"
"\n\n"
"Here are some things you might want to try:\n"
"- instead of `if s`, use `if not s.is_empty()`\n"
"- instead of `s1 and s2`, use `s1 & s2`\n"
"- instead of `s1 or s2`, use `s1 | s2`\n"
"- instead of `s in [y, z]`, use `s.is_in([y, z])`\n"
)
raise TypeError(msg)
def __getstate__(self) -> bytes:
return self._s.__getstate__()
def __setstate__(self, state: bytes) -> None:
self._s = Series()._s # Initialize with a dummy
self._s.__setstate__(state)
def __str__(self) -> str:
s_repr: str = self._s.as_str()
return s_repr.replace("Series", f"{self.__class__.__name__}", 1)
def __repr__(self) -> str:
return self.__str__()
def __len__(self) -> int:
return self.len()
def __and__(self, other: Series) -> Self:
if not isinstance(other, Series):
other = Series([other])
return self._from_pyseries(self._s.bitand(other._s))
def __rand__(self, other: Series) -> Series:
if not isinstance(other, Series):
other = Series([other])
return other & self
def __or__(self, other: Series) -> Self:
if not isinstance(other, Series):
other = Series([other])
return self._from_pyseries(self._s.bitor(other._s))
def __ror__(self, other: Series) -> Series:
if not isinstance(other, Series):
other = Series([other])
return other | self
def __xor__(self, other: Series) -> Self:
if not isinstance(other, Series):
other = Series([other])
return self._from_pyseries(self._s.bitxor(other._s))
def __rxor__(self, other: Series) -> Series:
if not isinstance(other, Series):
other = Series([other])
return other ^ self
def _comp(self, other: Any, op: ComparisonOperator) -> Series:
# special edge-case; boolean broadcast series (eq/neq) is its own result
if self.dtype == Boolean and isinstance(other, bool) and op in ("eq", "neq"):
if (other is True and op == "eq") or (other is False and op == "neq"):
return self.clone()
elif (other is False and op == "eq") or (other is True and op == "neq"):
return ~self
elif isinstance(other, float) and self.dtype.is_integer():
# require upcast when comparing int series to float value
self = self.cast(Float64)
f = get_ffi_func(op + "_<>", Float64, self._s)
assert f is not None
return self._from_pyseries(f(other))
elif isinstance(other, datetime):
if self.dtype == Date:
# require upcast when comparing date series to datetime
self = self.cast(Datetime("us"))
time_unit = "us"
elif self.dtype == Datetime:
# Use local time zone info
time_zone = self.dtype.time_zone # type: ignore[attr-defined]
if str(other.tzinfo) != str(time_zone):
msg = f"Datetime time zone {other.tzinfo!r} does not match Series timezone {time_zone!r}"
raise TypeError(msg)
time_unit = self.dtype.time_unit # type: ignore[attr-defined]
else:
msg = f"cannot compare datetime.datetime to Series of type {self.dtype}"
raise ValueError(msg)
ts = datetime_to_int(other, time_unit) # type: ignore[arg-type]
f = get_ffi_func(op + "_<>", Int64, self._s)
assert f is not None
return self._from_pyseries(f(ts))
elif isinstance(other, time) and self.dtype == Time:
d = time_to_int(other)
f = get_ffi_func(op + "_<>", Int64, self._s)
assert f is not None
return self._from_pyseries(f(d))
elif isinstance(other, timedelta) and self.dtype == Duration:
time_unit = self.dtype.time_unit # type: ignore[attr-defined]
td = timedelta_to_int(other, time_unit) # type: ignore[arg-type]
f = get_ffi_func(op + "_<>", Int64, self._s)
assert f is not None
return self._from_pyseries(f(td))
elif self.dtype in [Categorical, Enum] and not isinstance(other, Series):
other = Series([other])
elif isinstance(other, date) and self.dtype == Date:
d = date_to_int(other)
f = get_ffi_func(op + "_<>", Int32, self._s)
assert f is not None
return self._from_pyseries(f(d))
if isinstance(other, Sequence) and not isinstance(other, str):
if self.dtype in (List, Array):
other = [other]
other = Series("", other)
if other.dtype == Null:
other.cast(self.dtype)
if isinstance(other, Series):
return self._from_pyseries(getattr(self._s, op)(other._s))
if other is not None:
other = maybe_cast(other, self.dtype)
f = get_ffi_func(op + "_<>", self.dtype, self._s)
if f is None:
return NotImplemented
return self._from_pyseries(f(other))
@overload # type: ignore[override]
def __eq__(self, other: Expr) -> Expr: ... # type: ignore[overload-overlap]
@overload
def __eq__(self, other: Any) -> Series: ...
def __eq__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__eq__(other)
return self._comp(other, "eq")
@overload # type: ignore[override]
def __ne__(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def __ne__(self, other: Any) -> Series: ...
def __ne__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__ne__(other)
return self._comp(other, "neq")
@overload
def __gt__(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def __gt__(self, other: Any) -> Series: ...
def __gt__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__gt__(other)
return self._comp(other, "gt")
@overload
def __lt__(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def __lt__(self, other: Any) -> Series: ...
def __lt__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__lt__(other)
return self._comp(other, "lt")
@overload
def __ge__(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def __ge__(self, other: Any) -> Series: ...
def __ge__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__ge__(other)
return self._comp(other, "gt_eq")
@overload
def __le__(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def __le__(self, other: Any) -> Series: ...
def __le__(self, other: Any) -> Series | Expr:
warn_null_comparison(other)
if isinstance(other, pl.Expr):
return F.lit(self).__le__(other)
return self._comp(other, "lt_eq")
@overload
def le(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def le(self, other: Any) -> Series: ...
def le(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series <= other`."""
return self.__le__(other)
@overload
def lt(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def lt(self, other: Any) -> Series: ...
def lt(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series < other`."""
return self.__lt__(other)
@overload
def eq(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def eq(self, other: Any) -> Series: ...
def eq(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series == other`."""
return self.__eq__(other)
@overload
def eq_missing(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def eq_missing(self, other: Any) -> Series: ...
def eq_missing(self, other: Any) -> Series | Expr:
"""
Method equivalent of equality operator `series == other` where `None == None`.
This differs from the standard `ne` where null values are propagated.
Parameters
----------
other
A literal or expression value to compare with.
See Also
--------
ne_missing
eq
Examples
--------
>>> s1 = pl.Series("a", [333, 200, None])
>>> s2 = pl.Series("a", [100, 200, None])
>>> s1.eq(s2)
shape: (3,)
Series: 'a' [bool]
[
false
true
null
]
>>> s1.eq_missing(s2)
shape: (3,)
Series: 'a' [bool]
[
false
true
true
]
"""
if isinstance(other, pl.Expr):
return F.lit(self).eq_missing(other)
return self.to_frame().select(F.col(self.name).eq_missing(other)).to_series()
@overload
def ne(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def ne(self, other: Any) -> Series: ...
def ne(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series != other`."""
return self.__ne__(other)
@overload
def ne_missing(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def ne_missing(self, other: Any) -> Series: ...
def ne_missing(self, other: Any) -> Series | Expr:
"""
Method equivalent of equality operator `series != other` where `None == None`.
This differs from the standard `ne` where null values are propagated.
Parameters
----------
other
A literal or expression value to compare with.
See Also
--------
eq_missing
ne
Examples
--------
>>> s1 = pl.Series("a", [333, 200, None])
>>> s2 = pl.Series("a", [100, 200, None])
>>> s1.ne(s2)
shape: (3,)
Series: 'a' [bool]
[
true
false
null
]
>>> s1.ne_missing(s2)
shape: (3,)
Series: 'a' [bool]
[
true
false
false
]
"""
if isinstance(other, pl.Expr):
return F.lit(self).ne_missing(other)
return self.to_frame().select(F.col(self.name).ne_missing(other)).to_series()
@overload
def ge(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def ge(self, other: Any) -> Series: ...
def ge(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series >= other`."""
return self.__ge__(other)
@overload
def gt(self, other: Expr) -> Expr: # type: ignore[overload-overlap]
...
@overload
def gt(self, other: Any) -> Series: ...
def gt(self, other: Any) -> Series | Expr:
"""Method equivalent of operator expression `series > other`."""
return self.__gt__(other)
def _arithmetic(self, other: Any, op_s: str, op_ffi: str) -> Self:
if isinstance(other, pl.Expr):
# expand pl.lit, pl.datetime, pl.duration Exprs to compatible Series
other = self.to_frame().select_seq(other).to_series()
elif other is None:
other = pl.Series("", [None])
if isinstance(other, Series):
return self._from_pyseries(getattr(self._s, op_s)(other._s))
elif _check_for_numpy(other) and isinstance(other, np.ndarray):
return self._from_pyseries(getattr(self._s, op_s)(Series(other)._s))
elif (
isinstance(other, (float, date, datetime, timedelta, str))
and not self.dtype.is_float()
):
_s = sequence_to_pyseries(self.name, [other])
if "rhs" in op_ffi:
return self._from_pyseries(getattr(_s, op_s)(self._s))
else:
return self._from_pyseries(getattr(self._s, op_s)(_s))