-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathframe.py
3794 lines (3308 loc) · 122 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
"""
import os
import typing as tp
from datetime import timedelta
from io import BytesIO, StringIO
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Iterator,
Optional,
Sequence,
TextIO,
Tuple,
Type,
Union,
)
import numpy as np
try:
import pyarrow as pa
import pyarrow.compute
import pyarrow.parquet
_PYARROW_AVAILABLE = True
except ImportError:
_PYARROW_AVAILABLE = False
import polars as pl
from polars.internals.construction import (
arrow_to_pydf,
dict_to_pydf,
numpy_to_pydf,
pandas_to_pydf,
sequence_to_pydf,
series_to_pydf,
)
try:
from polars.polars import PyDataFrame, PySeries
_DOCUMENTING = False
except ImportError:
_DOCUMENTING = True
from .._html import NotebookFormatter
from ..datatypes import DTYPES, Boolean, DataType, UInt32, pytype_to_polars_type
from ..utils import _process_null_values
try:
import pandas as pd
_PANDAS_AVAILABLE = True
except ImportError:
_PANDAS_AVAILABLE = False
__all__ = [
"DataFrame",
]
def wrap_df(df: "PyDataFrame") -> "DataFrame":
return DataFrame._from_pydf(df)
def _prepare_other_arg(other: Any) -> "pl.Series":
# if not a series create singleton series such that it will broadcast
if not isinstance(other, pl.Series):
if isinstance(other, str):
pass
elif isinstance(other, Sequence):
raise ValueError("Operation not supported.")
other = pl.Series("", [other])
return other
class DataFrame:
"""
A DataFrame is a two-dimensional data structure that represents data as a table
with rows and columns.
Parameters
----------
data : dict, Sequence, ndarray, Series, or pandas.DataFrame
Two-dimensional data in various forms. dict must contain Sequences.
Sequence may contain Series or other Sequences.
columns : Sequence of str, default None
Column labels to use for resulting DataFrame. If specified, overrides any
labels already present in the data. Must match data dimensions.
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.
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 dtype is automatically inferred as a polars Int64:
>>> df.dtypes
[<class 'polars.datatypes.Int64'>, <class 'polars.datatypes.Int64'>]
In order to specify dtypes for your columns, initialize the DataFrame with a list
of Series instead:
>>> data = [pl.Series('col1', [1, 2], dtype=pl.Float32),
... pl.Series('col2', [3, 4], dtype=pl.Int64)]
>>> df2 = pl.DataFrame(series)
>>> df2
shape: (2, 2)
╭──────┬──────╮
│ col1 ┆ col2 │
│ --- ┆ --- │
│ f32 ┆ i64 │
╞══════╪══════╡
│ 1 ┆ 3 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2 ┆ 4 │
╰──────┴──────╯
Constructing a DataFrame from a numpy ndarray, specifying column names:
>>> data = np.array([(1, 2), (3, 4)])
>>> df3 = pl.DataFrame(data, columns=['a', 'b'], orient='col')
>>> df3
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]]
>>> df4 = pl.DataFrame(data, columns=['a', 'b', 'c'])
>>> df4
shape: (2, 3)
╭─────┬─────┬─────╮
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 3 │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 4 ┆ 5 ┆ 6 │
╰─────┴─────┴─────╯
"""
def __init__(
self,
data: Optional[
Union[
Dict[str, Sequence[Any]],
Sequence[Any],
np.ndarray,
"pa.Table",
"pd.DataFrame",
"pl.Series",
]
] = None,
columns: Optional[Sequence[str]] = None,
orient: Optional[str] = None,
):
if data is None:
self._df = dict_to_pydf({}, columns=columns)
elif isinstance(data, dict):
self._df = dict_to_pydf(data, columns=columns)
elif isinstance(data, np.ndarray):
self._df = numpy_to_pydf(data, columns=columns, orient=orient)
elif _PYARROW_AVAILABLE and isinstance(data, pa.Table):
self._df = arrow_to_pydf(data, columns=columns)
elif isinstance(data, Sequence) and not isinstance(data, str):
self._df = sequence_to_pydf(data, columns=columns, orient=orient)
elif isinstance(data, pl.Series):
self._df = series_to_pydf(data, columns=columns)
elif _PANDAS_AVAILABLE and isinstance(data, pd.DataFrame):
if not _PYARROW_AVAILABLE:
raise ImportError(
"'pyarrow' is required for converting a pandas DataFrame to a polars DataFrame."
)
self._df = pandas_to_pydf(data, columns=columns)
else:
raise ValueError("DataFrame constructor not called properly.")
@classmethod
def _from_pydf(cls, py_df: "PyDataFrame") -> "DataFrame":
"""
Construct Polars DataFrame from FFI PyDataFrame object.
"""
df = cls.__new__(cls)
df._df = py_df
return df
@classmethod
def _from_dicts(cls, data: Sequence[Dict[str, Any]]) -> "DataFrame":
pydf = PyDataFrame.read_dicts(data)
return DataFrame._from_pydf(pydf)
@classmethod
def _from_dict(
cls,
data: Dict[str, Sequence[Any]],
columns: Optional[Sequence[str]] = None,
) -> "DataFrame":
"""
Construct a DataFrame from a dictionary of sequences.
Parameters
----------
data : dict of sequences
Two-dimensional data represented as a dictionary. dict must contain
Sequences.
columns : Sequence of str, default None
Column labels to use for resulting DataFrame. If specified, overrides any
labels already present in the data. Must match data dimensions.
Returns
-------
DataFrame
"""
return cls._from_pydf(dict_to_pydf(data, columns=columns))
@classmethod
def _from_records(
cls,
data: Union[np.ndarray, Sequence[Sequence[Any]]],
columns: Optional[Sequence[str]] = None,
orient: Optional[str] = None,
) -> "DataFrame":
"""
Construct a DataFrame from a numpy ndarray or sequence of sequences.
Parameters
----------
data : numpy ndarray or Sequence of sequences
Two-dimensional data represented as numpy ndarray or sequence of sequences.
columns : Sequence of str, default None
Column labels to use for resulting DataFrame. Must match data dimensions.
If not specified, columns will be named `column_0`, `column_1`, etc.
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.
Returns
-------
DataFrame
"""
if isinstance(data, np.ndarray):
pydf = numpy_to_pydf(data, columns=columns, orient=orient)
else:
pydf = sequence_to_pydf(data, columns=columns, orient=orient)
return cls._from_pydf(pydf)
@classmethod
def _from_arrow(
cls,
data: "pa.Table",
columns: Optional[Sequence[str]] = None,
rechunk: bool = True,
) -> "DataFrame":
"""
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 : numpy ndarray or Sequence of sequences
Two-dimensional data represented as Arrow table.
columns : Sequence of str, default None
Column labels to use for resulting DataFrame. Must match data dimensions.
If not specified, existing Array table columns are used, with missing names
named as `column_0`, `column_1`, etc.
rechunk : bool, default True
Make sure that all data is contiguous.
Returns
-------
DataFrame
"""
return cls._from_pydf(arrow_to_pydf(data, columns=columns, rechunk=rechunk))
@classmethod
def _from_pandas(
cls,
data: "pd.DataFrame",
columns: Optional[Sequence[str]] = None,
rechunk: bool = True,
nan_to_none: bool = True,
) -> "DataFrame":
"""
Construct a Polars DataFrame from a pandas DataFrame.
Parameters
----------
data : pandas DataFrame
Two-dimensional data represented as a pandas DataFrame.
columns : Sequence of str, default None
Column labels to use for resulting DataFrame. If specified, overrides any
labels already present in the data. Must match data dimensions.
rechunk : bool, default True
Make sure that all data is contiguous.
nan_to_none : bool, default True
If data contains NaN values PyArrow will convert the NaN to None
Returns
-------
DataFrame
"""
return cls._from_pydf(
pandas_to_pydf(
data, columns=columns, rechunk=rechunk, nan_to_none=nan_to_none
)
)
@staticmethod
def read_csv(
file: Union[str, BinaryIO, bytes],
infer_schema_length: Optional[int] = 100,
batch_size: int = 64,
has_headers: bool = True,
ignore_errors: bool = False,
stop_after_n_rows: Optional[int] = None,
skip_rows: int = 0,
projection: Optional[tp.List[int]] = None,
sep: str = ",",
columns: Optional[tp.List[str]] = None,
rechunk: bool = True,
encoding: str = "utf8",
n_threads: Optional[int] = None,
dtype: Union[Dict[str, Type[DataType]], tp.List[Type[DataType]], None] = None,
low_memory: bool = False,
comment_char: Optional[str] = None,
quote_char: Optional[str] = r'"',
null_values: Optional[Union[str, tp.List[str], Dict[str, str]]] = None,
parse_dates: bool = True,
) -> "DataFrame":
"""
Read a CSV file into a Dataframe.
Parameters
----------
file
Path to a file or a file like object. Any valid filepath can be used. Example: `file.csv`.
infer_schema_length
Maximum number of lines to read to infer schema. If set to 0, all columns will be read as pl.Utf8.
If set to `None`, a full table scan will be done (slow).
batch_size
Number of lines to read into the buffer at once. Modify this to change performance.
has_headers
Indicate if first row of dataset is header or not. If set to False first row will be set to `column_x`,
`x` being an enumeration over every column in the dataset.
ignore_errors
Try to keep reading lines if some lines yield errors.
stop_after_n_rows
After n rows are read from the CSV, it stops reading.
During multi-threaded parsing, an upper bound of `n` rows
cannot be guaranteed.
skip_rows
Start reading after `skip_rows`.
projection
Indexes of columns to select. Note that column indexes count from zero.
sep
Character to use as delimiter in the file.
columns
Columns to project/ select.
rechunk
Make sure that all columns are contiguous in memory by aggregating the chunks into a single array.
encoding
Allowed encodings: `utf8`, `utf8-lossy`. Lossy means that invalid utf8 values are replaced with `�` character.
n_threads
Number of threads to use in csv parsing. Defaults to the number of physical cpu's of your system.
dtype
Overwrite the dtypes during inference.
low_memory
Reduce memory usage in expense of performance.
comment_char
character that indicates the start of a comment line, for instance '#'.
quote_char
single byte character that is used for csv quoting, default = ''. Set to None to turn special handling and escaping
of quotes off.
null_values
Values to interpret as null values. You can provide a:
- str -> all values encountered equal to this string will be null
- tp.List[str] -> A null value per column.
- Dict[str, str] -> A dictionary that maps column name to a null value string.
Returns
-------
DataFrame
Examples
--------
>>> df = pl.read_csv('file.csv', sep=';', stop_after_n_rows=25)
"""
self = DataFrame.__new__(DataFrame)
path: Optional[str]
if isinstance(file, str):
path = file
else:
path = None
if isinstance(file, BytesIO):
file = file.getvalue()
if isinstance(file, StringIO):
file = file.getvalue().encode()
dtype_list: Optional[tp.List[Tuple[str, Type[DataType]]]] = None
dtype_slice: Optional[tp.List[Type[DataType]]] = None
if dtype is not None:
if isinstance(dtype, dict):
dtype_list = []
for k, v in dtype.items():
dtype_list.append((k, pytype_to_polars_type(v)))
elif isinstance(dtype, list):
dtype_slice = dtype
else:
raise ValueError("dtype arg should be list or dict")
processed_null_values = _process_null_values(null_values)
self._df = PyDataFrame.read_csv(
file,
infer_schema_length,
batch_size,
has_headers,
ignore_errors,
stop_after_n_rows,
skip_rows,
projection,
sep,
rechunk,
columns,
encoding,
n_threads,
path,
dtype_list,
dtype_slice,
low_memory,
comment_char,
quote_char,
processed_null_values,
parse_dates,
)
return self
@staticmethod
def read_parquet(
file: Union[str, BinaryIO],
stop_after_n_rows: Optional[int] = None,
) -> "DataFrame":
"""
Read into a DataFrame from a parquet file.
Parameters
----------
file
Path to a file or a file like object. Any valid filepath can be used.
stop_after_n_rows
Only read specified number of rows of the dataset. After `n` stops reading.
"""
self = DataFrame.__new__(DataFrame)
self._df = PyDataFrame.read_parquet(file, stop_after_n_rows)
return self
@staticmethod
def read_ipc(file: Union[str, BinaryIO]) -> "DataFrame":
"""
Read into a DataFrame from Arrow IPC stream format. This is also called the feather format.
Parameters
----------
file
Path to a file or a file like object.
Returns
-------
DataFrame
"""
self = DataFrame.__new__(DataFrame)
self._df = PyDataFrame.read_ipc(file)
return self
@staticmethod
def read_json(file: Union[str, BytesIO]) -> "DataFrame":
"""
Read into a DataFrame from JSON format.
Parameters
----------
file
Path to a file or a file like object.
"""
if not isinstance(file, str):
file = file.read().decode("utf8")
self = DataFrame.__new__(DataFrame)
self._df = PyDataFrame.read_json(file)
return self
def to_arrow(self) -> "pa.Table":
"""
Collect the underlying arrow arrays in an Arrow Table.
This operation is mostly zero copy.
Data types that do copy:
- CategoricalType
"""
if not _PYARROW_AVAILABLE:
raise ImportError(
"'pyarrow' is required for converting a polars DataFrame to an Arrow Table."
)
record_batches = self._df.to_arrow()
return pa.Table.from_batches(record_batches)
def to_dict(
self, as_series: bool = True
) -> Union[Dict[str, "pl.Series"], Dict[str, tp.List[Any]]]:
"""
Convert DataFrame to a dictionary mapping column name to values.
Parameters
----------
as_series
True -> Values are series
False -> Values are List[Any]
Examples
--------
>>> df = pl.DataFrame({
>>> "A": [1, 2, 3, 4, 5],
>>> "fruits": ["banana", "banana", "apple", "apple", "banana"],
>>> "B": [5, 4, 3, 2, 1],
>>> "cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
>>> "optional": [28, 300, None, 2, -30],
>>> })
shape: (5, 5)
┌─────┬──────────┬─────┬──────────┬──────────┐
│ A ┆ fruits ┆ B ┆ cars ┆ optional │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ i64 ┆ str ┆ i64 │
╞═════╪══════════╪═════╪══════════╪══════════╡
│ 1 ┆ "banana" ┆ 5 ┆ "beetle" ┆ 28 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ "banana" ┆ 4 ┆ "audi" ┆ 300 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ "apple" ┆ 3 ┆ "beetle" ┆ null │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ "apple" ┆ 2 ┆ "beetle" ┆ 2 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ "banana" ┆ 1 ┆ "beetle" ┆ -30 │
└─────┴──────────┴─────┴──────────┴──────────┘
>>> df.to_dict(as_series=False)
{'A': [1, 2, 3, 4, 5],
'fruits': ['banana', 'banana', 'apple', 'apple', 'banana'],
'B': [5, 4, 3, 2, 1],
'cars': ['beetle', 'audi', 'beetle', 'beetle', 'beetle'],
'optional': [28, 300, None, 2, -30]}
>>> df.to_dict(as_series=True)
{'A': shape: (5,)
Series: 'A' [i64]
[
1
2
3
4
5
],
'fruits': shape: (5,)
...
Series: 'optional' [i64]
[
28
300
null
2
-30
]}
"""
if as_series:
return {s.name: s for s in self}
else:
return {s.name: s.to_list() for s in self}
def to_json(
self,
file: Optional[Union[BytesIO, str, Path]] = None,
pretty: bool = False,
to_string: bool = False,
) -> Optional[str]:
"""
Serialize to JSON representation.
Parameters
----------
file
Write to this file instead of returning an string.
pretty
Pretty serialize json.
to_string
Ignore file argument and return a string.
"""
if to_string or file is None:
file = BytesIO()
self._df.to_json(file, pretty)
file.seek(0)
return file.read().decode("utf8")
else:
self._df.to_json(file, pretty)
return None
def to_pandas(
self, *args: Any, date_as_object: bool = False, **kwargs: Any
) -> "pd.DataFrame": # noqa: F821
"""
Cast to a Pandas DataFrame. This requires that Pandas is installed.
This operation clones data.
Parameters
----------
args
Arguments will be sent to pyarrow.Table.to_pandas.
date_as_object
Cast dates to objects. If False, convert to datetime64[ns] dtype.
kwargs
Arguments will be sent to pyarrow.Table.to_pandas.
Examples
--------
>>> import pandas
>>> df = pl.DataFrame({
"foo": [1, 2, 3],
"bar": [6, 7, 8],
"ham": ['a', 'b', 'c']
})
>>> pandas_df = df.to_pandas()
>>> type(pandas_df)
pandas.core.frame.DataFrame
"""
return self.to_arrow().to_pandas(*args, date_as_object=date_as_object, **kwargs)
def to_csv(
self,
file: Optional[Union[TextIO, str, Path]] = None,
has_headers: bool = True,
sep: str = ",",
) -> Optional[str]:
"""
Write Dataframe to comma-separated values file (csv).
Parameters
---
file
File path to which the file should be written.
has_headers
Whether or not to include header in the CSV output.
sep
Separate CSV fields with this symbol.
Examples
--------
>>> df = pl.DataFrame({
>>> "foo": [1, 2, 3, 4, 5],
>>> "bar": [6, 7, 8, 9, 10],
>>> "ham": ['a', 'b', 'c', 'd','e']
>>> })
>>> df.to_csv('new_file.csv', sep=',')
"""
if file is None:
buffer = BytesIO()
self._df.to_csv(buffer, has_headers, ord(sep))
return str(buffer.getvalue(), encoding="utf-8")
if isinstance(file, Path):
file = str(file)
self._df.to_csv(file, has_headers, ord(sep))
return None
def to_ipc(self, file: Union[BinaryIO, str, Path]) -> None:
"""
Write to Arrow IPC binary stream, or a feather file.
Parameters
----------
file
File path to which the file should be written.
"""
if isinstance(file, Path):
file = str(file)
self._df.to_ipc(file)
def to_dicts(self) -> tp.List[Dict[str, Any]]:
pydf = self._df
names = self.columns
return [
{k: v for k, v in zip(names, pydf.row_tuple(i))}
for i in range(0, self.height)
]
def transpose(
self, include_header: bool = False, header_name: str = "column"
) -> "pl.DataFrame":
"""
Transpose a DataFrame over the diagonal.
Parameters
----------
include_header:
If set, the column names will be added as first column.
header_name:
If `include_header` is set, this determines the name of the column that will be inserted
Notes
-----
This is a very expensive operation. Perhaps you can do it differently.
Returns
-------
DataFrame
"""
return wrap_df(self._df.transpose(include_header, header_name))
def to_parquet(
self,
file: Union[str, Path],
compression: str = "snappy",
use_pyarrow: bool = False,
**kwargs: Any,
) -> None:
"""
Write the DataFrame disk in parquet format.
Parameters
----------
file
File path to which the file should be written.
compression
Compression method. Choose one of:
- "uncompressed" (not supported by pyarrow)
- "snappy"
- "gzip"
- "lzo"
- "brotli"
- "lz4"
- "zstd"
use_pyarrow
Use C++ parquet implementation vs rust parquet implementation.
At the moment C++ supports more features.
**kwargs are passed to pyarrow.parquet.write_table
"""
if isinstance(file, Path):
file = str(file)
if use_pyarrow:
if not _PYARROW_AVAILABLE:
raise ImportError(
"'pyarrow' is required when using 'to_parquet(..., use_pyarrow=True)'."
)
tbl = self.to_arrow()
data = {}
for i, column in enumerate(tbl):
# extract the name before casting
if column._name is None:
name = f"column_{i}"
else:
name = column._name
data[name] = column
tbl = pa.table(data)
pa.parquet.write_table(
table=tbl, where=file, compression=compression, **kwargs
)
else:
self._df.to_parquet(file, compression)
def to_numpy(self) -> np.ndarray:
"""
Convert DataFrame to a 2d numpy array.
This operation clones data.
Examples
--------
>>> df = pl.DataFrame({
>>> "foo": [1, 2, 3],
>>> "bar": [6, 7, 8],
>>> "ham": ['a', 'b', 'c']
>>> })
>>> numpy_array = df.to_numpy()
>>> type(numpy_array)
numpy.ndarray
"""
return np.vstack(
[self.select_at_idx(i).to_numpy() for i in range(self.width)]
).T
def __getstate__(self): # type: ignore
return self.get_columns()
def __setstate__(self, state): # type: ignore
self._df = DataFrame(state)._df
def __mul__(self, other: Any) -> "DataFrame":
other = _prepare_other_arg(other)
return wrap_df(self._df.mul(other._s))
def __truediv__(self, other: Any) -> "DataFrame":
other = _prepare_other_arg(other)
return wrap_df(self._df.div(other._s))
def __add__(self, other: Any) -> "DataFrame":
other = _prepare_other_arg(other)
return wrap_df(self._df.add(other._s))
def __sub__(self, other: Any) -> "DataFrame":
other = _prepare_other_arg(other)
return wrap_df(self._df.sub(other._s))
def __str__(self) -> str:
return self._df.as_str()
def __repr__(self) -> str:
return self.__str__()
def __getattr__(self, item: Any) -> "PySeries":
"""
Access columns as attribute.
"""
try:
return pl.eager.series.wrap_s(self._df.column(item))
except RuntimeError:
raise AttributeError(f"{item} not found")
def __iter__(self) -> Iterator[Any]:
return self.get_columns().__iter__()
def find_idx_by_name(self, name: str) -> int:
"""
Find the index of a column by name.
Parameters
----------
name
Name of the column to find.
Examples
--------
>>> df = pl.DataFrame({
>>> "foo": [1, 2, 3],
>>> "bar": [6, 7, 8],
>>> "ham": ['a', 'b', 'c']
>>> })
>>> df.find_idx_by_name("ham"))
2
"""
return self._df.find_idx_by_name(name)
def _pos_idx(self, idx: int, dim: int) -> int:
if idx >= 0:
return idx
else:
return self.shape[dim] + idx
def __getitem__(self, item: Any) -> Any:
"""
Does quite a lot. Read the comments.
"""
if hasattr(item, "_pyexpr"):
return self.select(item)
if isinstance(item, np.ndarray):
item = pl.Series("", item)
# select rows and columns at once
# every 2d selection, i.e. tuple is row column order, just like numpy
if isinstance(item, tuple):
row_selection, col_selection = item
# df[:, unknown]
if isinstance(row_selection, slice):
# multiple slices
# df[:, :]
if isinstance(col_selection, slice):
# slice can be
# by index
# [1:8]
# or by column name
# ["foo":"bar"]
# first we make sure that the slice is by index
start = col_selection.start
stop = col_selection.stop
if isinstance(col_selection.start, str):
start = self.find_idx_by_name(col_selection.start)
if isinstance(col_selection.stop, str):
stop = self.find_idx_by_name(col_selection.stop) + 1
col_selection = slice(start, stop, col_selection.step)
df = self.__getitem__(self.columns[col_selection])
return df[row_selection]
# slice and boolean mask
# df[:2, [True, False, True]]
if isinstance(col_selection, (Sequence, pl.Series)):
if (
isinstance(col_selection[0], bool)
or isinstance(col_selection, pl.Series)
and col_selection.dtype() == pl.Boolean
):
df = self.__getitem__(row_selection)
select = []
for col, valid in zip(df.columns, col_selection):
if valid:
select.append(col)
return df.select(select)
# single slice
# df[:, unknown]
series = self.__getitem__(col_selection)
# s[:]
pl.eager.series.wrap_s(series[row_selection])
# df[2, :] (select row as df)
if isinstance(row_selection, int):
if isinstance(col_selection, (slice, list, np.ndarray)):
df = self[:, col_selection]
return df.slice(row_selection, 1)
# df[2, "a"]
if isinstance(col_selection, str):
return self[col_selection][row_selection]
# column selection can be "a" and ["a", "b"]
if isinstance(col_selection, str):
col_selection = [col_selection]
# df[:, 1]
if isinstance(col_selection, int):
series = self.select_at_idx(col_selection)
return series[row_selection]
if isinstance(col_selection, list):
# df[:, [1, 2]]
# select by column indexes
if isinstance(col_selection[0], int):
series = [self.select_at_idx(i) for i in col_selection]
df = DataFrame(series)
return df[row_selection]