/
frame.py
10660 lines (9461 loc) · 389 KB
/
frame.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
"""Module containing logic related to eager DataFrames."""
from __future__ import annotations
import contextlib
import os
import random
from collections import OrderedDict, defaultdict
from collections.abc import Sized
from io import BytesIO, StringIO, TextIOWrapper
from operator import itemgetter
from pathlib import Path
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Collection,
Generator,
Iterable,
Iterator,
Mapping,
NoReturn,
Sequence,
TypeVar,
Union,
cast,
get_args,
overload,
)
import polars._reexport as pl
from polars import functions as F
from polars._utils.construction import (
arrow_to_pydf,
dataframe_to_pydf,
dict_to_pydf,
iterable_to_pydf,
numpy_to_idxs,
numpy_to_pydf,
pandas_to_pydf,
sequence_to_pydf,
series_to_pydf,
)
from polars._utils.convert import parse_as_duration_string
from polars._utils.deprecation import (
deprecate_function,
deprecate_nonkeyword_arguments,
deprecate_parameter_as_positional,
deprecate_renamed_function,
deprecate_renamed_parameter,
deprecate_saturating,
issue_deprecation_warning,
)
from polars._utils.parse_expr_input import parse_as_expression
from polars._utils.unstable import issue_unstable_warning, unstable
from polars._utils.various import (
is_bool_sequence,
is_int_sequence,
is_str_sequence,
normalize_filepath,
parse_version,
range_to_slice,
scale_bytes,
warn_null_comparison,
)
from polars._utils.wrap import wrap_expr, wrap_ldf, wrap_s
from polars.dataframe._html import NotebookFormatter
from polars.dataframe.group_by import DynamicGroupBy, GroupBy, RollingGroupBy
from polars.datatypes import (
INTEGER_DTYPES,
N_INFER_DEFAULT,
Boolean,
Float64,
Object,
String,
)
from polars.dependencies import (
_HVPLOT_AVAILABLE,
_PANDAS_AVAILABLE,
_PYARROW_AVAILABLE,
_check_for_numpy,
_check_for_pandas,
_check_for_pyarrow,
hvplot,
import_optional,
)
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,
NoRowsReturnedError,
TooManyRowsReturnedError,
)
from polars.functions import col, lit
from polars.io.csv._utils import _check_arg_is_1byte
from polars.io.spreadsheet._write_utils import (
_unpack_multi_column_dict,
_xl_apply_conditional_formats,
_xl_inject_sparklines,
_xl_setup_table_columns,
_xl_setup_table_options,
_xl_setup_workbook,
_xl_unique_table_name,
_XLFormatCache,
)
from polars.selectors import _expand_selector_dicts, _expand_selectors
from polars.slice import PolarsSlice
from polars.type_aliases import DbWriteMode
with contextlib.suppress(ImportError): # Module not available when building docs
from polars.polars import dtype_str_repr as _dtype_str_repr
from polars.polars import write_clipboard_string as _write_clipboard_string
if TYPE_CHECKING:
import sys
from datetime import timedelta
from io import IOBase
from typing import Literal
import deltalake
from hvplot.plotting.core import hvPlotTabularPolars
from xlsxwriter import Workbook
from polars import DataType, Expr, LazyFrame, Series
from polars.interchange.dataframe import PolarsDataFrame
from polars.polars import PyDataFrame
from polars.type_aliases import (
AsofJoinStrategy,
AvroCompression,
ClosedInterval,
ColumnFormatDict,
ColumnNameOrSelector,
ColumnTotalsDefinition,
ColumnWidthsDefinition,
ComparisonOperator,
ConditionalFormatDict,
CsvQuoteStyle,
DbWriteEngine,
FillNullStrategy,
FrameInitTypes,
IndexOrder,
IntoExpr,
IntoExprColumn,
IpcCompression,
JoinStrategy,
JoinValidation,
Label,
NullStrategy,
OneOrMoreDataTypes,
Orientation,
ParquetCompression,
PivotAgg,
PolarsDataType,
RollingInterpolationMethod,
RowTotalsDefinition,
SchemaDefinition,
SchemaDict,
SelectorType,
SizeUnit,
StartBy,
UniqueKeepStrategy,
UnstackDirection,
)
if sys.version_info >= (3, 10):
from typing import Concatenate, ParamSpec, TypeAlias
else:
from typing_extensions import Concatenate, ParamSpec, TypeAlias
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
# these aliases are used to annotate DataFrame.__getitem__()
# MultiRowSelector indexes into the vertical axis and
# MultiColSelector indexes into the horizontal axis
# NOTE: wrapping these as strings is necessary for Python <3.10
MultiRowSelector: TypeAlias = Union[slice, range, "list[int]", "Series"]
MultiColSelector: TypeAlias = Union[
slice, range, "list[int]", "list[str]", "list[bool]", "Series"
]
T = TypeVar("T")
P = ParamSpec("P")
class DataFrame:
"""
Two-dimensional data structure representing data as a table with rows and columns.
Parameters
----------
data : dict, Sequence, ndarray, Series, or pandas.DataFrame
Two-dimensional data in various forms; dict input must contain Sequences,
Generators, or a `range`. Sequence may contain Series or other Sequences.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The schema of the resulting DataFrame. The schema may be declared in several
ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
If set to `None` (default), the schema is inferred from the data.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the schema param will be overridden.
The number of entries in the schema should match the underlying data
dimensions, unless a sequence of dictionaries is being passed, in which case
a *partial* schema can be declared to prevent specific fields from being loaded.
strict : bool, default True
Throw an error if any `data` value does not exactly match the given or inferred
data type for that column. 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.
orient : {'col', 'row'}, default None
Whether to interpret two-dimensional data as columns or as rows. If None,
the orientation is inferred by matching the columns and data dimensions. If
this does not yield conclusive results, column orientation is used.
infer_schema_length : int or None
The maximum number of rows to scan for schema inference. If set to `None`, the
full data may be scanned *(this can be slow)*. This parameter only applies if
the input data is a sequence or generator of rows; other input is read as-is.
nan_to_null : bool, default False
If the data comes from one or more numpy arrays, can optionally convert input
data np.nan values to null instead. This is a no-op for all other input data.
Notes
-----
Polars explicitly does not support subclassing of its core data types. See
the following GitHub issue for possible workarounds:
https://github.com/pola-rs/polars/issues/2846#issuecomment-1711799869
Examples
--------
Constructing a DataFrame from a dictionary:
>>> data = {"a": [1, 2], "b": [3, 4]}
>>> df = pl.DataFrame(data)
>>> df
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
Notice that the dtypes are automatically inferred as polars Int64:
>>> df.dtypes
[Int64, Int64]
To specify a more detailed/specific frame schema you can supply the `schema`
parameter with a dictionary of (name,dtype) pairs...
>>> data = {"col1": [0, 2], "col2": [3, 7]}
>>> df2 = pl.DataFrame(data, schema={"col1": pl.Float32, "col2": pl.Int64})
>>> df2
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 0.0 ┆ 3 │
│ 2.0 ┆ 7 │
└──────┴──────┘
...a sequence of (name,dtype) pairs...
>>> data = {"col1": [1, 2], "col2": [3, 4]}
>>> df3 = pl.DataFrame(data, schema=[("col1", pl.Float32), ("col2", pl.Int64)])
>>> df3
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 1.0 ┆ 3 │
│ 2.0 ┆ 4 │
└──────┴──────┘
...or a list of typed Series.
>>> data = [
... pl.Series("col1", [1, 2], dtype=pl.Float32),
... pl.Series("col2", [3, 4], dtype=pl.Int64),
... ]
>>> df4 = pl.DataFrame(data)
>>> df4
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 1.0 ┆ 3 │
│ 2.0 ┆ 4 │
└──────┴──────┘
Constructing a DataFrame from a numpy ndarray, specifying column names:
>>> import numpy as np
>>> data = np.array([(1, 2), (3, 4)], dtype=np.int64)
>>> df5 = pl.DataFrame(data, schema=["a", "b"], orient="col")
>>> df5
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
Constructing a DataFrame from a list of lists, row orientation inferred:
>>> data = [[1, 2, 3], [4, 5, 6]]
>>> df6 = pl.DataFrame(data, schema=["a", "b", "c"])
>>> df6
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┘
"""
_df: PyDataFrame
_accessors: ClassVar[set[str]] = {"plot"}
def __init__(
self,
data: FrameInitTypes | None = None,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
strict: bool = True,
orient: Orientation | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
nan_to_null: bool = False,
):
if data is None:
self._df = dict_to_pydf(
{}, schema=schema, schema_overrides=schema_overrides
)
elif isinstance(data, dict):
self._df = dict_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
nan_to_null=nan_to_null,
)
elif isinstance(data, (list, tuple, Sequence)):
self._df = sequence_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
infer_schema_length=infer_schema_length,
)
elif isinstance(data, pl.Series):
self._df = series_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif _check_for_numpy(data) and isinstance(data, np.ndarray):
self._df = numpy_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
nan_to_null=nan_to_null,
)
elif _check_for_pyarrow(data) and isinstance(data, pa.Table):
self._df = arrow_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif _check_for_pandas(data) and isinstance(data, pd.DataFrame):
self._df = pandas_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
elif not isinstance(data, Sized) and isinstance(data, (Generator, Iterable)):
self._df = iterable_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
infer_schema_length=infer_schema_length,
)
elif isinstance(data, pl.DataFrame):
self._df = dataframe_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, strict=strict
)
else:
msg = (
f"DataFrame constructor called with unsupported type {type(data).__name__!r}"
" for the `data` parameter"
)
raise TypeError(msg)
@classmethod
def _from_pydf(cls, py_df: PyDataFrame) -> Self:
"""Construct Polars DataFrame from FFI PyDataFrame object."""
df = cls.__new__(cls)
df._df = py_df
return df
@classmethod
def _from_arrow(
cls,
data: pa.Table | pa.RecordBatch,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
) -> Self:
"""
Construct a DataFrame from an Arrow table.
This operation will be zero copy for the most part. Types that are not
supported by Polars may be cast to the closest supported type.
Parameters
----------
data : arrow Table, RecordBatch, or sequence of sequences
Data representing an Arrow Table or RecordBatch.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The DataFrame schema may be declared in several ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the columns param will be overridden.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
"""
return cls._from_pydf(
arrow_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
rechunk=rechunk,
)
)
@classmethod
def _from_pandas(
cls,
data: pd.DataFrame,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
nan_to_null: bool = True,
include_index: bool = False,
) -> Self:
"""
Construct a Polars DataFrame from a pandas DataFrame.
Parameters
----------
data : pandas DataFrame
Two-dimensional data represented as a pandas DataFrame.
schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
The DataFrame schema may be declared in several ways:
* As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
* As a list of column names; in this case types are automatically inferred.
* As a list of (name,type) pairs; this is equivalent to the dictionary form.
If you supply a list of column names that does not match the names in the
underlying data, the names given here will overwrite them. The number
of names given in the schema should match the underlying data dimensions.
schema_overrides : dict, default None
Support type specification or override of one or more columns; note that
any dtypes inferred from the columns param will be overridden.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
nan_to_null : bool, default True
If the data contains NaN values they will be converted to null/None.
include_index : bool, default False
Load any non-default pandas indexes as columns.
"""
return cls._from_pydf(
pandas_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
rechunk=rechunk,
nan_to_null=nan_to_null,
include_index=include_index,
)
)
def _replace(self, column: str, new_column: Series) -> Self:
"""Replace a column by a new Series (in place)."""
self._df.replace(column, new_column._s)
return self
@property
def plot(self) -> hvPlotTabularPolars:
"""
Create a plot namespace.
Polars does not implement plotting logic itself, but instead defers to
hvplot. Please see the `hvplot reference gallery <https://hvplot.holoviz.org/reference/index.html>`_
for more information and documentation.
Examples
--------
Scatter plot:
>>> df = pl.DataFrame(
... {
... "length": [1, 4, 6],
... "width": [4, 5, 6],
... "species": ["setosa", "setosa", "versicolor"],
... }
... )
>>> df.plot.scatter(x="length", y="width", by="species") # doctest: +SKIP
Line plot:
>>> from datetime import date
>>> df = pl.DataFrame(
... {
... "date": [date(2020, 1, 2), date(2020, 1, 3), date(2020, 1, 4)],
... "stock_1": [1, 4, 6],
... "stock_2": [1, 5, 2],
... }
... )
>>> df.plot.line(x="date", y=["stock_1", "stock_2"]) # doctest: +SKIP
For more info on what you can pass, you can use ``hvplot.help``:
>>> import hvplot # doctest: +SKIP
>>> hvplot.help("scatter") # doctest: +SKIP
"""
if not _HVPLOT_AVAILABLE or parse_version(hvplot.__version__) < parse_version(
"0.9.1"
):
msg = "hvplot>=0.9.1 is required for `.plot`"
raise ModuleUpgradeRequired(msg)
hvplot.post_patch()
return hvplot.plotting.core.hvPlotTabularPolars(self)
@property
def shape(self) -> tuple[int, int]:
"""
Get the shape of the DataFrame.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5]})
>>> df.shape
(5, 1)
"""
return self._df.shape()
@property
def height(self) -> int:
"""
Get the height of the DataFrame.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5]})
>>> df.height
5
"""
return self._df.height()
@property
def width(self) -> int:
"""
Get the width of the DataFrame.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5]})
>>> df.width
1
"""
return self._df.width()
@property
def columns(self) -> list[str]:
"""
Get or set column names.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6, 7, 8],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.columns
['foo', 'bar', 'ham']
Set column names:
>>> df.columns = ["apple", "banana", "orange"]
>>> df
shape: (3, 3)
┌───────┬────────┬────────┐
│ apple ┆ banana ┆ orange │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═══════╪════════╪════════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└───────┴────────┴────────┘
"""
return self._df.columns()
@columns.setter
def columns(self, names: Sequence[str]) -> None:
"""
Change the column names of the `DataFrame`.
Parameters
----------
names
A list with new names for the `DataFrame`.
The length of the list should be equal to the width of the `DataFrame`.
"""
self._df.set_column_names(names)
@property
def dtypes(self) -> list[DataType]:
"""
Get the datatypes of the columns of this DataFrame.
The datatypes can also be found in column headers when printing the DataFrame.
See Also
--------
schema : Returns a {colname:dtype} mapping.
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.dtypes
[Int64, Float64, String]
>>> df
shape: (3, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6.0 ┆ a │
│ 2 ┆ 7.0 ┆ b │
│ 3 ┆ 8.0 ┆ c │
└─────┴─────┴─────┘
"""
return self._df.dtypes()
@property
def flags(self) -> dict[str, dict[str, bool]]:
"""
Get flags that are set on the columns of this DataFrame.
Returns
-------
dict
Mapping from column names to column flags.
"""
return {name: self[name].flags for name in self.columns}
@property
def schema(self) -> OrderedDict[str, DataType]:
"""
Get a dict[column name, DataType].
Examples
--------
>>> df = pl.DataFrame(
... {
... "foo": [1, 2, 3],
... "bar": [6.0, 7.0, 8.0],
... "ham": ["a", "b", "c"],
... }
... )
>>> df.schema
OrderedDict({'foo': Int64, 'bar': Float64, 'ham': String})
"""
return OrderedDict(zip(self.columns, self.dtypes))
def __array__(self, dtype: Any = None) -> np.ndarray[Any, Any]:
"""
Numpy __array__ interface protocol.
Ensures that `np.asarray(pl.DataFrame(..))` works as expected, see
https://numpy.org/devdocs/user/basics.interoperability.html#the-array-method.
"""
if dtype:
return self.to_numpy().__array__(dtype)
else:
return self.to_numpy().__array__()
def __dataframe__(
self,
nan_as_null: bool = False, # noqa: FBT001
allow_copy: bool = True, # noqa: FBT001
) -> PolarsDataFrame:
"""
Convert to a dataframe object implementing the dataframe interchange protocol.
Parameters
----------
nan_as_null
Overwrite null values in the data with `NaN`.
.. warning::
This functionality has not been implemented and the parameter will be
removed in a future version.
Setting this to `True` will raise a `NotImplementedError`.
allow_copy
Allow memory to be copied to perform the conversion. If set to `False`,
causes conversions that are not zero-copy to fail.
Notes
-----
Details on the Python dataframe interchange protocol:
https://data-apis.org/dataframe-protocol/latest/index.html
Examples
--------
Convert a Polars DataFrame to a generic dataframe object and access some
properties.
>>> df = pl.DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["x", "y"]})
>>> dfi = df.__dataframe__()
>>> dfi.num_rows()
2
>>> dfi.get_column(1).dtype
(<DtypeKind.FLOAT: 2>, 64, 'g', '=')
"""
if nan_as_null:
msg = (
"functionality for `nan_as_null` has not been implemented and the"
" parameter will be removed in a future version"
"\n\nUse the default `nan_as_null=False`."
)
raise NotImplementedError(msg)
from polars.interchange.dataframe import PolarsDataFrame
return PolarsDataFrame(self, allow_copy=allow_copy)
def _comp(self, other: Any, op: ComparisonOperator) -> DataFrame:
"""Compare a DataFrame with another object."""
if isinstance(other, DataFrame):
return self._compare_to_other_df(other, op)
else:
return self._compare_to_non_df(other, op)
def _compare_to_other_df(
self,
other: DataFrame,
op: ComparisonOperator,
) -> DataFrame:
"""Compare a DataFrame with another DataFrame."""
if self.columns != other.columns:
msg = "DataFrame columns do not match"
raise ValueError(msg)
if self.shape != other.shape:
msg = "DataFrame dimensions do not match"
raise ValueError(msg)
suffix = "__POLARS_CMP_OTHER"
other_renamed = other.select(F.all().name.suffix(suffix))
combined = F.concat([self, other_renamed], how="horizontal")
if op == "eq":
expr = [F.col(n) == F.col(f"{n}{suffix}") for n in self.columns]
elif op == "neq":
expr = [F.col(n) != F.col(f"{n}{suffix}") for n in self.columns]
elif op == "gt":
expr = [F.col(n) > F.col(f"{n}{suffix}") for n in self.columns]
elif op == "lt":
expr = [F.col(n) < F.col(f"{n}{suffix}") for n in self.columns]
elif op == "gt_eq":
expr = [F.col(n) >= F.col(f"{n}{suffix}") for n in self.columns]
elif op == "lt_eq":
expr = [F.col(n) <= F.col(f"{n}{suffix}") for n in self.columns]
else:
msg = f"unexpected comparison operator {op!r}"
raise ValueError(msg)
return combined.select(expr)
def _compare_to_non_df(
self,
other: Any,
op: ComparisonOperator,
) -> DataFrame:
"""Compare a DataFrame with a non-DataFrame object."""
warn_null_comparison(other)
if op == "eq":
return self.select(F.all() == other)
elif op == "neq":
return self.select(F.all() != other)
elif op == "gt":
return self.select(F.all() > other)
elif op == "lt":
return self.select(F.all() < other)
elif op == "gt_eq":
return self.select(F.all() >= other)
elif op == "lt_eq":
return self.select(F.all() <= other)
else:
msg = f"unexpected comparison operator {op!r}"
raise ValueError(msg)
def _div(self, other: Any, *, floordiv: bool) -> DataFrame:
if isinstance(other, pl.Series):
if floordiv:
return self.select(F.all() // lit(other))
return self.select(F.all() / lit(other))
elif not isinstance(other, DataFrame):
s = _prepare_other_arg(other, length=len(self))
other = DataFrame([s.alias(f"n{i}") for i in range(len(self.columns))])
orig_dtypes = other.dtypes
other = self._cast_all_from_to(other, INTEGER_DTYPES, Float64)
df = self._from_pydf(self._df.div_df(other._df))
df = (
df
if not floordiv
else df.with_columns([s.floor() for s in df if s.dtype.is_float()])
)
if floordiv:
int_casts = [
col(column).cast(tp)
for i, (column, tp) in enumerate(self.schema.items())
if tp.is_integer() and orig_dtypes[i].is_integer()
]
if int_casts:
return df.with_columns(int_casts)
return df
def _cast_all_from_to(
self, df: DataFrame, from_: frozenset[PolarsDataType], to: PolarsDataType
) -> DataFrame:
casts = [s.cast(to).alias(s.name) for s in df if s.dtype in from_]
return df.with_columns(casts) if casts else df
def __floordiv__(self, other: DataFrame | Series | int | float) -> DataFrame:
return self._div(other, floordiv=True)
def __truediv__(self, other: DataFrame | Series | int | float) -> DataFrame:
return self._div(other, floordiv=False)
def __bool__(self) -> NoReturn:
msg = (
"the truth value of a DataFrame is ambiguous"
"\n\nHint: to check if a DataFrame contains any values, use `is_empty()`."
)
raise TypeError(msg)
def __eq__(self, other: Any) -> DataFrame: # type: ignore[override]
return self._comp(other, "eq")
def __ne__(self, other: Any) -> DataFrame: # type: ignore[override]
return self._comp(other, "neq")
def __gt__(self, other: Any) -> DataFrame:
return self._comp(other, "gt")
def __lt__(self, other: Any) -> DataFrame:
return self._comp(other, "lt")
def __ge__(self, other: Any) -> DataFrame:
return self._comp(other, "gt_eq")
def __le__(self, other: Any) -> DataFrame:
return self._comp(other, "lt_eq")
def __getstate__(self) -> list[Series]:
return self.get_columns()
def __setstate__(self, state: list[Series]) -> None:
self._df = DataFrame(state)._df
def __mul__(self, other: DataFrame | Series | int | float) -> Self:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.mul_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.mul(other._s))
def __rmul__(self, other: DataFrame | Series | int | float) -> Self:
return self * other
def __add__(
self, other: DataFrame | Series | int | float | bool | str
) -> DataFrame:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.add_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.add(other._s))
def __radd__( # type: ignore[misc]
self, other: DataFrame | Series | int | float | bool | str
) -> DataFrame:
if isinstance(other, str):
return self.select((lit(other) + F.col("*")).name.keep())
return self + other
def __sub__(self, other: DataFrame | Series | int | float) -> Self:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.sub_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.sub(other._s))
def __mod__(self, other: DataFrame | Series | int | float) -> Self:
if isinstance(other, DataFrame):
return self._from_pydf(self._df.rem_df(other._df))
other = _prepare_other_arg(other)
return self._from_pydf(self._df.rem(other._s))
def __str__(self) -> str:
return self._df.as_str()
def __repr__(self) -> str:
return self.__str__()
def __contains__(self, key: str) -> bool:
return key in self.columns
def __iter__(self) -> Iterator[Series]:
return self.iter_columns()
def __reversed__(self) -> Iterator[Series]:
return reversed(self.get_columns())
def _pos_idx(self, idx: int, dim: int) -> int:
if idx >= 0:
return idx
else:
return self.shape[dim] + idx
def _take_with_series(self, s: Series) -> DataFrame:
return self._from_pydf(self._df.take_with_series(s._s))
@overload
def __getitem__(self, item: str) -> Series: ...
@overload
def __getitem__(