-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
frame.py
10915 lines (9707 loc) · 392 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.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,
py_type_to_dtype,
)
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._utils import _is_glob_pattern, _is_local_file
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
from polars.utils._construction import (
arrow_to_pydf,
dict_to_pydf,
frame_to_pydf,
iterable_to_pydf,
numpy_to_idxs,
numpy_to_pydf,
pandas_to_pydf,
sequence_to_pydf,
series_to_pydf,
)
from polars.utils._parse_expr_input import parse_as_expression
from polars.utils._wrap import wrap_expr, wrap_ldf, wrap_s
from polars.utils.convert import _timedelta_to_pl_duration
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.unstable import issue_unstable_warning, unstable
from polars.utils.various import (
_prepare_row_index_args,
_process_null_values,
handle_projection_columns,
is_bool_sequence,
is_int_sequence,
is_str_sequence,
normalize_filepath,
parse_version,
range_to_slice,
scale_bytes,
warn_null_comparison,
)
with contextlib.suppress(ImportError): # Module not available when building docs
from polars.polars import PyDataFrame
from polars.polars import dtype_str_repr as _dtype_str_repr
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.type_aliases import (
AsofJoinStrategy,
AvroCompression,
ClosedInterval,
ColumnFormatDict,
ColumnNameOrSelector,
ColumnTotalsDefinition,
ColumnWidthsDefinition,
ComparisonOperator,
ConditionalFormatDict,
CsvEncoding,
CsvQuoteStyle,
DbWriteEngine,
FillNullStrategy,
FrameInitTypes,
IndexOrder,
IntoExpr,
IntoExprColumn,
IpcCompression,
JoinStrategy,
JoinValidation,
Label,
NullStrategy,
OneOrMoreDataTypes,
Orientation,
ParallelStrategy,
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 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 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.
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 is 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.
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 │
└─────┴─────┴─────┘
Notes
-----
Some methods internally convert the DataFrame into a LazyFrame before collecting
the results back into a DataFrame. This can lead to unexpected behavior when using
a subclassed DataFrame. For example,
>>> class MyDataFrame(pl.DataFrame):
... pass
>>> isinstance(MyDataFrame().lazy().collect(), MyDataFrame)
False
"""
_accessors: ClassVar[set[str]] = {"plot"}
def __init__(
self,
data: FrameInitTypes | None = None,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
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,
nan_to_null=nan_to_null,
)
elif isinstance(data, (list, tuple, Sequence)):
self._df = sequence_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
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
)
elif _check_for_numpy(data) and isinstance(data, np.ndarray):
self._df = numpy_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
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
)
elif _check_for_pandas(data) and isinstance(data, pd.DataFrame):
self._df = pandas_to_pydf(
data, schema=schema, schema_overrides=schema_overrides
)
elif not isinstance(data, Sized) and isinstance(data, (Generator, Iterable)):
self._df = iterable_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
orient=orient,
infer_schema_length=infer_schema_length,
)
elif isinstance(data, pl.DataFrame):
self._df = frame_to_pydf(
data, schema=schema, schema_overrides=schema_overrides
)
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_dict(
cls,
data: Mapping[str, Sequence[object] | Mapping[str, Sequence[object]] | Series],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
) -> Self:
"""
Construct a DataFrame from a dictionary of sequences.
Parameters
----------
data : dict of sequences
Two-dimensional data represented as a dictionary. dict must contain
Sequences.
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.
"""
return cls._from_pydf(
dict_to_pydf(data, schema=schema, schema_overrides=schema_overrides)
)
@classmethod
def _from_records(
cls,
data: Sequence[Any],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
orient: Orientation | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
) -> Self:
"""
Construct a DataFrame from a sequence of sequences.
See Also
--------
polars.io.from_records
"""
return cls._from_pydf(
sequence_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
orient=orient,
infer_schema_length=infer_schema_length,
)
)
@classmethod
def _from_numpy(
cls,
data: np.ndarray[Any, Any],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
orient: Orientation | None = None,
) -> Self:
"""
Construct a DataFrame from a numpy ndarray.
Parameters
----------
data : numpy ndarray
Two-dimensional data represented as a numpy ndarray.
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.
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.
"""
return cls._from_pydf(
numpy_to_pydf(
data, schema=schema, schema_overrides=schema_overrides, orient=orient
)
)
@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,
)
)
@classmethod
def _read_csv(
cls,
source: str | Path | IO[bytes] | bytes,
*,
has_header: bool = True,
columns: Sequence[int] | Sequence[str] | None = None,
separator: str = ",",
comment_prefix: str | None = None,
quote_char: str | None = '"',
skip_rows: int = 0,
dtypes: None | (SchemaDict | Sequence[PolarsDataType]) = None,
schema: None | SchemaDict = None,
null_values: str | Sequence[str] | dict[str, str] | None = None,
missing_utf8_is_empty_string: bool = False,
ignore_errors: bool = False,
try_parse_dates: bool = False,
n_threads: int | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
batch_size: int = 8192,
n_rows: int | None = None,
encoding: CsvEncoding = "utf8",
low_memory: bool = False,
rechunk: bool = True,
skip_rows_after_header: int = 0,
row_index_name: str | None = None,
row_index_offset: int = 0,
sample_size: int = 1024,
eol_char: str = "\n",
raise_if_empty: bool = True,
truncate_ragged_lines: bool = False,
) -> DataFrame:
"""
Read a CSV file into a DataFrame.
Use `pl.read_csv` to dispatch to this method.
See Also
--------
polars.io.read_csv
"""
self = cls.__new__(cls)
path: str | None
if isinstance(source, (str, Path)):
path = normalize_filepath(source)
else:
path = None
if isinstance(source, BytesIO):
source = source.getvalue()
if isinstance(source, StringIO):
source = source.getvalue().encode()
dtype_list: Sequence[tuple[str, PolarsDataType]] | None = None
dtype_slice: Sequence[PolarsDataType] | None = None
if dtypes is not None:
if isinstance(dtypes, dict):
dtype_list = []
for k, v in dtypes.items():
dtype_list.append((k, py_type_to_dtype(v)))
elif isinstance(dtypes, Sequence):
dtype_slice = dtypes
else:
msg = f"`dtypes` should be of type list or dict, got {type(dtypes).__name__!r}"
raise TypeError(msg)
processed_null_values = _process_null_values(null_values)
if isinstance(columns, str):
columns = [columns]
if isinstance(source, str) and _is_glob_pattern(source):
dtypes_dict = None
if dtype_list is not None:
dtypes_dict = dict(dtype_list)
if dtype_slice is not None:
msg = (
"cannot use glob patterns and unnamed dtypes as `dtypes` argument"
"\n\nUse `dtypes`: Mapping[str, Type[DataType]]"
)
raise ValueError(msg)
from polars import scan_csv
scan = scan_csv(
source,
has_header=has_header,
separator=separator,
comment_prefix=comment_prefix,
quote_char=quote_char,
skip_rows=skip_rows,
dtypes=dtypes_dict,
schema=schema,
null_values=null_values,
missing_utf8_is_empty_string=missing_utf8_is_empty_string,
ignore_errors=ignore_errors,
infer_schema_length=infer_schema_length,
n_rows=n_rows,
low_memory=low_memory,
rechunk=rechunk,
skip_rows_after_header=skip_rows_after_header,
row_index_name=row_index_name,
row_index_offset=row_index_offset,
eol_char=eol_char,
raise_if_empty=raise_if_empty,
truncate_ragged_lines=truncate_ragged_lines,
)
if columns is None:
return scan.collect()
elif is_str_sequence(columns, allow_str=False):
return scan.select(columns).collect()
else:
msg = (
"cannot use glob patterns and integer based projection as `columns` argument"
"\n\nUse columns: List[str]"
)
raise ValueError(msg)
projection, columns = handle_projection_columns(columns)
self._df = PyDataFrame.read_csv(
source,
infer_schema_length,
batch_size,
has_header,
ignore_errors,
n_rows,
skip_rows,
projection,
separator,
rechunk,
columns,
encoding,
n_threads,
path,
dtype_list,
dtype_slice,
low_memory,
comment_prefix,
quote_char,
processed_null_values,
missing_utf8_is_empty_string,
try_parse_dates,
skip_rows_after_header,
_prepare_row_index_args(row_index_name, row_index_offset),
sample_size=sample_size,
eol_char=eol_char,
raise_if_empty=raise_if_empty,
truncate_ragged_lines=truncate_ragged_lines,
schema=schema,
)
return self
@classmethod
def _read_parquet(
cls,
source: str | Path | IO[bytes] | bytes,
*,
columns: Sequence[int] | Sequence[str] | None = None,
n_rows: int | None = None,
parallel: ParallelStrategy = "auto",
row_index_name: str | None = None,
row_index_offset: int = 0,
low_memory: bool = False,
use_statistics: bool = True,
rechunk: bool = True,
) -> DataFrame:
"""
Read into a DataFrame from a parquet file.
Use `pl.read_parquet` to dispatch to this method.
See Also
--------
polars.io.read_parquet
"""
if isinstance(source, (str, Path)):
source = normalize_filepath(source)
if isinstance(columns, str):
columns = [columns]
if isinstance(source, str) and _is_glob_pattern(source):
from polars import scan_parquet
scan = scan_parquet(
source,
n_rows=n_rows,
rechunk=True,
parallel=parallel,
row_index_name=row_index_name,
row_index_offset=row_index_offset,
low_memory=low_memory,
)
if columns is None:
return scan.collect()
elif is_str_sequence(columns, allow_str=False):
return scan.select(columns).collect()
else:
msg = (
"cannot use glob patterns and integer based projection as `columns` argument"
"\n\nUse columns: List[str]"
)
raise TypeError(msg)
projection, columns = handle_projection_columns(columns)
self = cls.__new__(cls)
self._df = PyDataFrame.read_parquet(
source,
columns,
projection,
n_rows,
parallel,
_prepare_row_index_args(row_index_name, row_index_offset),
low_memory=low_memory,
use_statistics=use_statistics,
rechunk=rechunk,
)
return self
@classmethod
def _read_avro(
cls,
source: str | Path | IO[bytes] | bytes,
*,
columns: Sequence[int] | Sequence[str] | None = None,
n_rows: int | None = None,
) -> Self:
"""
Read into a DataFrame from Apache Avro format.
Parameters
----------
source
Path to a file or a file-like object (by file-like object, we refer to
objects that have a `read()` method, such as a file handler (e.g.
via builtin `open` function) or `BytesIO`).
columns
Columns.
n_rows
Stop reading from Apache Avro file after reading `n_rows`.
"""
if isinstance(source, (str, Path)):
source = normalize_filepath(source)
projection, columns = handle_projection_columns(columns)
self = cls.__new__(cls)
self._df = PyDataFrame.read_avro(source, columns, projection, n_rows)
return self
@classmethod
def _read_ipc(
cls,
source: str | Path | IO[bytes] | bytes,
*,
columns: Sequence[int] | Sequence[str] | None = None,
n_rows: int | None = None,
row_index_name: str | None = None,
row_index_offset: int = 0,
rechunk: bool = True,
memory_map: bool = True,
) -> Self:
"""
Read into a DataFrame from Arrow IPC file format.
See "File or Random Access format" on https://arrow.apache.org/docs/python/ipc.html.
Arrow IPC files are also known as Feather (v2) files.
Parameters
----------
source
Path to a file or a file-like object (by file-like object, we refer to
objects that have a `read()` method, such as a file handler (e.g.
via builtin `open` function) or `BytesIO`).
columns
Columns to select. Accepts a list of column indices (starting at zero) or a
list of column names.
n_rows
Stop reading from IPC file after reading `n_rows`.
row_index_name
Row index name.
row_index_offset
Row index offset.
rechunk
Make sure that all data is contiguous.
memory_map
Memory map the file
"""
if isinstance(source, (str, Path)):
source = normalize_filepath(source)
if isinstance(columns, str):
columns = [columns]
if (
isinstance(source, str)
and _is_glob_pattern(source)
and _is_local_file(source)
):
from polars import scan_ipc
scan = scan_ipc(
source,
n_rows=n_rows,
rechunk=rechunk,
row_index_name=row_index_name,
row_index_offset=row_index_offset,
memory_map=memory_map,
)
if columns is None:
df = scan.collect()
elif is_str_sequence(columns, allow_str=False):
df = scan.select(columns).collect()
else:
msg = (
"cannot use glob patterns and integer based projection as `columns` argument"
"\n\nUse columns: List[str]"
)
raise TypeError(msg)
return cls._from_pydf(df._df)
projection, columns = handle_projection_columns(columns)
self = cls.__new__(cls)
self._df = PyDataFrame.read_ipc(
source,
columns,
projection,
n_rows,
_prepare_row_index_args(row_index_name, row_index_offset),
memory_map=memory_map,
)
return self
@classmethod
def _read_ipc_stream(
cls,
source: str | Path | IO[bytes] | bytes,
*,
columns: Sequence[int] | Sequence[str] | None = None,
n_rows: int | None = None,
row_index_name: str | None = None,
row_index_offset: int = 0,
rechunk: bool = True,
) -> Self:
"""
Read into a DataFrame from Arrow IPC record batch stream format.
See "Streaming format" on https://arrow.apache.org/docs/python/ipc.html.
Parameters
----------
source
Path to a file or a file-like object (by file-like object, we refer to
objects that have a `read()` method, such as a file handler (e.g.
via builtin `open` function) or `BytesIO`).
columns
Columns to select. Accepts a list of column indices (starting at zero) or a
list of column names.
n_rows
Stop reading from IPC stream after reading `n_rows`.
row_index_name
Row index name.
row_index_offset
Row index offset.
rechunk
Make sure that all data is contiguous.
"""
if isinstance(source, (str, Path)):
source = normalize_filepath(source)
if isinstance(columns, str):
columns = [columns]
projection, columns = handle_projection_columns(columns)
self = cls.__new__(cls)
self._df = PyDataFrame.read_ipc_stream(
source,