-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
convert.py
830 lines (723 loc) · 30 KB
/
convert.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
from __future__ import annotations
import io
import itertools
import re
from typing import TYPE_CHECKING, Any, Iterable, Mapping, Sequence, overload
import polars._reexport as pl
from polars import functions as F
from polars._utils.construction.dataframe import (
arrow_to_pydf,
dict_to_pydf,
numpy_to_pydf,
pandas_to_pydf,
sequence_to_pydf,
)
from polars._utils.construction.series import arrow_to_pyseries, pandas_to_pyseries
from polars._utils.deprecation import deprecate_renamed_parameter
from polars._utils.various import _cast_repr_strings_with_schema
from polars._utils.wrap import wrap_df, wrap_s
from polars.datatypes import N_INFER_DEFAULT, Categorical, List, Object, String, Struct
from polars.dependencies import pandas as pd
from polars.dependencies import pyarrow as pa
from polars.exceptions import NoDataError
from polars.io import read_csv
if TYPE_CHECKING:
from polars import DataFrame, Series
from polars.dependencies import numpy as np
from polars.interchange.protocol import SupportsInterchange
from polars.type_aliases import Orientation, SchemaDefinition, SchemaDict
def from_dict(
data: Mapping[str, Sequence[object] | Mapping[str, Sequence[object]] | Series],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
strict: bool = True,
) -> DataFrame:
"""
Construct a DataFrame from a dictionary of sequences.
This operation clones data, unless you pass a `{str: pl.Series,}` dict.
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.
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.
Returns
-------
DataFrame
Examples
--------
>>> df = pl.from_dict({"a": [1, 2], "b": [3, 4]})
>>> df
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
"""
return wrap_df(
dict_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
)
)
def from_dicts(
data: Sequence[dict[str, Any]],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
strict: bool = True,
infer_schema_length: int | None = N_INFER_DEFAULT,
) -> DataFrame:
"""
Construct a DataFrame from a sequence of dictionaries. This operation clones data.
Parameters
----------
data
Sequence with dictionaries mapping column name to value
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 a list of column names is supplied that does NOT match the names in the
underlying data, the names given here will overwrite the actual fields in
the order that they appear - however, in this case it is typically clearer
to rename after loading the frame.
If you want to drop some of the fields found in the input dictionaries, a
*partial* schema can be declared, in which case omitted fields will not be
loaded. Similarly, you can extend the loaded frame with empty columns by
adding them to the schema.
schema_overrides : dict, default None
Support override of inferred types for one or more columns.
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.
infer_schema_length
The maximum number of rows to scan for schema inference.
If set to `None`, the full data may be scanned *(this is slow)*.
Returns
-------
DataFrame
Examples
--------
>>> data = [{"a": 1, "b": 4}, {"a": 2, "b": 5}, {"a": 3, "b": 6}]
>>> df = pl.from_dicts(data)
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
└─────┴─────┘
Declaring a partial `schema` will drop the omitted columns.
>>> df = pl.from_dicts(data, schema={"a": pl.Int32})
>>> df
shape: (3, 1)
┌─────┐
│ a │
│ --- │
│ i32 │
╞═════╡
│ 1 │
│ 2 │
│ 3 │
└─────┘
Can also use the `schema` param to extend the loaded columns with one
or more additional (empty) columns that are not present in the input dicts:
>>> pl.from_dicts(
... data,
... schema=["a", "b", "c", "d"],
... schema_overrides={"c": pl.Float64, "d": pl.String},
... )
shape: (3, 4)
┌─────┬─────┬──────┬──────┐
│ a ┆ b ┆ c ┆ d │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ f64 ┆ str │
╞═════╪═════╪══════╪══════╡
│ 1 ┆ 4 ┆ null ┆ null │
│ 2 ┆ 5 ┆ null ┆ null │
│ 3 ┆ 6 ┆ null ┆ null │
└─────┴─────┴──────┴──────┘
"""
if not data and not (schema or schema_overrides):
msg = "no data, cannot infer schema"
raise NoDataError(msg)
return pl.DataFrame(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
infer_schema_length=infer_schema_length,
)
def from_records(
data: Sequence[Any],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
strict: bool = True,
orient: Orientation | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
) -> DataFrame:
"""
Construct a DataFrame from a sequence of sequences. This operation clones data.
Note that this is slower than creating from columnar memory.
Parameters
----------
data : Sequence of sequences
Two-dimensional data represented as a sequence of 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.
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 : {None, 'col', 'row'}
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
The maximum number of rows to scan for schema inference.
If set to `None`, the full data may be scanned *(this is slow)*.
Returns
-------
DataFrame
Examples
--------
>>> data = [[1, 2, 3], [4, 5, 6]]
>>> df = pl.from_records(data, schema=["a", "b"])
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
└─────┴─────┘
"""
if not isinstance(data, Sequence):
msg = (
f"expected data of type Sequence, got {type(data).__name__!r}"
"\n\nHint: Try passing your data to the DataFrame constructor instead,"
" e.g. `pl.DataFrame(data)`."
)
raise TypeError(msg)
return wrap_df(
sequence_to_pydf(
data,
schema=schema,
schema_overrides=schema_overrides,
strict=strict,
orient=orient,
infer_schema_length=infer_schema_length,
)
)
def from_numpy(
data: np.ndarray[Any, Any],
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
orient: Orientation | None = None,
) -> DataFrame:
"""
Construct a DataFrame from a NumPy ndarray. This operation clones data.
Note that this is slower than creating from columnar memory.
Parameters
----------
data : :class:`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 : {None, 'col', 'row'}
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.
Returns
-------
DataFrame
Examples
--------
>>> import numpy as np
>>> data = np.array([[1, 2, 3], [4, 5, 6]])
>>> df = pl.from_numpy(data, schema=["a", "b"], orient="col")
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
└─────┴─────┘
"""
return wrap_df(
numpy_to_pydf(
data, schema=schema, orient=orient, schema_overrides=schema_overrides
)
)
# Note: we cannot @overload the typing (Series vs DataFrame) here, as pyarrow
# does not implement any support for type hints; attempts to hint here will
# simply result in mypy inferring "Any", which isn't useful...
def from_arrow(
data: (
pa.Table
| pa.Array
| pa.ChunkedArray
| pa.RecordBatch
| Iterable[pa.RecordBatch | pa.Table]
),
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
) -> DataFrame | Series:
"""
Create a DataFrame or Series from an Arrow Table or Array.
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 : :class:`pyarrow.Table`, :class:`pyarrow.Array`, one or more :class:`pyarrow.RecordBatch`
Data representing an Arrow Table, Array, or sequence of RecordBatches or Tables.
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.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
Returns
-------
DataFrame or Series
Examples
--------
Constructing a DataFrame from an Arrow Table:
>>> import pyarrow as pa
>>> data = pa.table({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> pl.from_arrow(data)
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 4 │
│ 2 ┆ 5 │
│ 3 ┆ 6 │
└─────┴─────┘
Constructing a Series from an Arrow Array:
>>> import pyarrow as pa
>>> data = pa.array([1, 2, 3])
>>> pl.from_arrow(data, schema={"s": pl.Int32})
shape: (3,)
Series: 's' [i32]
[
1
2
3
]
""" # noqa: W505
if isinstance(data, (pa.Table, pa.RecordBatch)):
return wrap_df(
arrow_to_pydf(
data=data,
rechunk=rechunk,
schema=schema,
schema_overrides=schema_overrides,
)
)
elif isinstance(data, (pa.Array, pa.ChunkedArray)):
name = getattr(data, "_name", "") or ""
s = wrap_s(arrow_to_pyseries(name, data, rechunk=rechunk))
s = pl.DataFrame(
data=s,
schema=schema,
schema_overrides=schema_overrides,
).to_series()
return s if (name or schema or schema_overrides) else s.alias("")
elif not data:
return pl.DataFrame(
schema=schema,
schema_overrides=schema_overrides,
)
if isinstance(data, Iterable):
pa_table = pa.Table.from_batches(
itertools.chain.from_iterable(
(b.to_batches() if isinstance(b, pa.Table) else [b]) for b in data
)
)
return wrap_df(
arrow_to_pydf(
data=pa_table,
rechunk=rechunk,
schema=schema,
schema_overrides=schema_overrides,
)
)
msg = f"expected PyArrow Table, Array, or one or more RecordBatches; got {type(data).__name__!r}"
raise TypeError(msg)
@overload
def from_pandas(
data: pd.DataFrame,
*,
schema_overrides: SchemaDict | None = ...,
rechunk: bool = ...,
nan_to_null: bool = ...,
include_index: bool = ...,
) -> DataFrame: ...
@overload
def from_pandas(
data: pd.Series[Any] | pd.Index[Any],
*,
schema_overrides: SchemaDict | None = ...,
rechunk: bool = ...,
nan_to_null: bool = ...,
include_index: bool = ...,
) -> Series: ...
def from_pandas(
data: pd.DataFrame | pd.Series[Any] | pd.Index[Any] | pd.DatetimeIndex,
*,
schema_overrides: SchemaDict | None = None,
rechunk: bool = True,
nan_to_null: bool = True,
include_index: bool = False,
) -> DataFrame | Series:
"""
Construct a Polars DataFrame or Series from a pandas DataFrame, Series, or Index.
This operation clones data.
This requires that :mod:`pandas` and :mod:`pyarrow` are installed.
Parameters
----------
data : :class:`pandas.DataFrame` or :class:`pandas.Series` or :class:`pandas.Index`
Data represented as a pandas DataFrame, Series, or Index.
schema_overrides : dict, default None
Support override of inferred types for one or more columns.
rechunk : bool, default True
Make sure that all data is in contiguous memory.
nan_to_null : bool, default True
If data contains `NaN` values PyArrow will convert the `NaN` to `None`
include_index : bool, default False
Load any non-default pandas indexes as columns.
.. note::
If the input is a pandas ``Series`` or ``DataFrame`` and has a nameless
index which just enumerates the rows, then it will not be included in the
result, regardless of this parameter. If you want to be sure to include it,
please call ``.reset_index()`` prior to calling this function.
Returns
-------
DataFrame
Examples
--------
Constructing a :class:`DataFrame` from a :class:`pandas.DataFrame`:
>>> import pandas as pd
>>> pd_df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
>>> df = pl.from_pandas(pd_df)
>>> df
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
│ 4 ┆ 5 ┆ 6 │
└─────┴─────┴─────┘
Constructing a Series from a :class:`pandas.Series`:
>>> import pandas as pd
>>> pd_series = pd.Series([1, 2, 3], name="pd")
>>> df = pl.from_pandas(pd_series)
>>> df
shape: (3,)
Series: 'pd' [i64]
[
1
2
3
]
"""
if isinstance(data, (pd.Series, pd.Index, pd.DatetimeIndex)):
return wrap_s(pandas_to_pyseries("", data, nan_to_null=nan_to_null))
elif isinstance(data, pd.DataFrame):
return wrap_df(
pandas_to_pydf(
data,
schema_overrides=schema_overrides,
rechunk=rechunk,
nan_to_null=nan_to_null,
include_index=include_index,
)
)
else:
msg = f"expected pandas DataFrame or Series, got {type(data).__name__!r}"
raise TypeError(msg)
@deprecate_renamed_parameter("tbl", "data", version="0.20.17")
def from_repr(data: str) -> DataFrame | Series:
"""
Construct a Polars DataFrame or Series from its string representation.
Parameters
----------
data
A string containing a polars DataFrame or Series repr; does not need
to be trimmed of whitespace (or leading prompts) as the repr will be
found/extracted automatically.
Notes
-----
This function handles the default UTF8_FULL and UTF8_FULL_CONDENSED DataFrame
tables (with or without rounded corners). Truncated columns/rows are omitted,
wrapped headers are accounted for, and dtypes automatically identified.
Currently compound/nested dtypes such as List and Struct are not supported;
neither are Object dtypes.
See Also
--------
polars.DataFrame.to_init_repr
polars.Series.to_init_repr
Examples
--------
From DataFrame table repr:
>>> df = pl.from_repr(
... '''
... Out[3]:
... shape: (1, 5)
... ┌───────────┬────────────┬───┬───────┬────────────────────────────────┐
... │ source_ac ┆ source_cha ┆ … ┆ ident ┆ timestamp │
... │ tor_id ┆ nnel_id ┆ ┆ --- ┆ --- │
... │ --- ┆ --- ┆ ┆ str ┆ datetime[μs, Asia/Tokyo] │
... │ i32 ┆ i64 ┆ ┆ ┆ │
... ╞═══════════╪════════════╪═══╪═══════╪════════════════════════════════╡
... │ 123456780 ┆ 9876543210 ┆ … ┆ a:b:c ┆ 2023-03-25 10:56:59.663053 JST │
... │ … ┆ … ┆ … ┆ … ┆ … │
... │ 803065983 ┆ 2055938745 ┆ … ┆ x:y:z ┆ 2023-03-25 12:38:18.050545 JST │
... └───────────┴────────────┴───┴───────┴────────────────────────────────┘
... '''
... )
>>> df
shape: (2, 4)
┌─────────────────┬───────────────────┬───────┬────────────────────────────────┐
│ source_actor_id ┆ source_channel_id ┆ ident ┆ timestamp │
│ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ i64 ┆ str ┆ datetime[μs, Asia/Tokyo] │
╞═════════════════╪═══════════════════╪═══════╪════════════════════════════════╡
│ 123456780 ┆ 9876543210 ┆ a:b:c ┆ 2023-03-25 10:56:59.663053 JST │
│ 803065983 ┆ 2055938745 ┆ x:y:z ┆ 2023-03-25 12:38:18.050545 JST │
└─────────────────┴───────────────────┴───────┴────────────────────────────────┘
From Series repr:
>>> s = pl.from_repr(
... '''
... shape: (3,)
... Series: 's' [bool]
... [
... true
... false
... true
... ]
... '''
... )
>>> s.to_list()
[True, False, True]
"""
# find DataFrame table...
m = re.search(r"([┌╭].*?[┘╯])", data, re.DOTALL)
if m is not None:
return _from_dataframe_repr(m)
# ...or Series in the given string
m = re.search(
pattern=r"(?:shape: (\(\d+,\))\n.*?)?Series:\s+([^\n]+)\s+\[([^\n]+)](.*)",
string=data,
flags=re.DOTALL,
)
if m is not None:
return _from_series_repr(m)
msg = "input string does not contain DataFrame or Series"
raise ValueError(msg)
def _from_dataframe_repr(m: re.Match[str]) -> DataFrame:
"""Reconstruct a DataFrame from a regex-matched table repr."""
from polars.datatypes.convert import dtype_short_repr_to_dtype
# extract elements from table structure
lines = m.group().split("\n")[1:-1]
rows = [
[re.sub(r"^[\W+]*│", "", elem).strip() for elem in row]
for row in [re.split("[┆|]", row.rstrip("│ ")) for row in lines]
if len(row) > 1 or not re.search("├[╌┼]+┤", row[0])
]
# determine beginning/end of the header block
table_body_start = 2
for idx, (elem, *_) in enumerate(rows):
if re.match(r"^\W*╞", elem):
table_body_start = idx
break
# handle headers with wrapped column names and determine headers/dtypes
header_block = ["".join(h).split("---") for h in zip(*rows[:table_body_start])]
dtypes: list[str | None]
if all(len(h) == 1 for h in header_block):
headers = [h[0] for h in header_block]
dtypes = [None] * len(headers)
else:
headers, dtypes = (list(h) for h in itertools.zip_longest(*header_block))
body = rows[table_body_start + 1 :]
no_dtypes = all(d is None for d in dtypes)
# transpose rows into columns, detect/omit truncated columns
coldata = list(zip(*(row for row in body if not all((e == "…") for e in row))))
for el in ("…", "..."):
if el in headers:
idx = headers.index(el)
for table_elem in (headers, dtypes):
table_elem.pop(idx) # type: ignore[attr-defined]
if coldata:
coldata.pop(idx)
# init cols as String Series, handle "null" -> None, create schema from repr dtype
data = [
pl.Series([(None if v == "null" else v) for v in cd], dtype=String)
for cd in coldata
]
schema = dict(zip(headers, (dtype_short_repr_to_dtype(d) for d in dtypes)))
if schema and data and (n_extend_cols := (len(schema) - len(data))) > 0:
empty_data = [None] * len(data[0])
data.extend((pl.Series(empty_data, dtype=String)) for _ in range(n_extend_cols))
for dtype in set(schema.values()):
if dtype in (List, Struct, Object):
msg = (
f"`from_repr` does not support data type {dtype.base_type().__name__!r}"
)
raise NotImplementedError(msg)
# construct DataFrame from string series and cast from repr to native dtype
df = pl.DataFrame(data=data, orient="col", schema=list(schema))
if no_dtypes:
if df.is_empty():
# if no dtypes *and* empty, default to string
return df.with_columns(F.all().cast(String))
else:
# otherwise, take a trip through our CSV inference logic
if all(tp == String for tp in df.schema.values()):
buf = io.BytesIO()
df.write_csv(file=buf)
df = read_csv(buf, new_columns=df.columns, try_parse_dates=True)
return df
elif schema and not data:
return df.cast(schema) # type: ignore[arg-type]
else:
return _cast_repr_strings_with_schema(df, schema)
def _from_series_repr(m: re.Match[str]) -> Series:
"""Reconstruct a Series from a regex-matched series repr."""
from polars.datatypes.convert import dtype_short_repr_to_dtype
shape = m.groups()[0]
name = m.groups()[1][1:-1]
length = int(shape[1:-2] if shape else -1)
dtype = dtype_short_repr_to_dtype(m.groups()[2])
if length == 0:
string_values = []
else:
string_values = [
v.strip()
for v in re.findall(r"[\s>#]*(?:\t|\s{4,})([^\n]*)\n", m.groups()[-1])
]
if string_values == ["[", "]"]:
string_values = []
elif string_values and string_values[0].lstrip("#> ") == "[":
string_values = string_values[1:]
values = string_values[:length] if length > 0 else string_values
values = [(None if v == "null" else v) for v in values if v not in ("…", "...")]
if not values:
return pl.Series(name=name, values=values, dtype=dtype)
else:
srs = pl.Series(name=name, values=values, dtype=String)
if dtype is None:
return srs
elif dtype in (Categorical, String):
return srs.str.replace('^"(.*)"$', r"$1").cast(dtype)
return _cast_repr_strings_with_schema(
srs.to_frame(), schema={srs.name: dtype}
).to_series()
def from_dataframe(df: SupportsInterchange, *, allow_copy: bool = True) -> DataFrame:
"""
Build a Polars DataFrame from any dataframe supporting the interchange protocol.
Parameters
----------
df
Object supporting the dataframe interchange protocol, i.e. must have implemented
the `__dataframe__` method.
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
Using a dedicated function like :func:`from_pandas` or :func:`from_arrow` is a more
efficient method of conversion.
Examples
--------
Convert a pandas dataframe to Polars through the interchange protocol.
>>> import pandas as pd
>>> df_pd = pd.DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["x", "y"]})
>>> dfi = df_pd.__dataframe__()
>>> pl.from_dataframe(dfi)
shape: (2, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 3.0 ┆ x │
│ 2 ┆ 4.0 ┆ y │
└─────┴─────┴─────┘
"""
from polars.interchange.from_dataframe import from_dataframe
return from_dataframe(df, allow_copy=allow_copy)