-
Notifications
You must be signed in to change notification settings - Fork 108
/
dataframe.py
1384 lines (1138 loc) · 51.8 KB
/
dataframe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar, Union
import pandas
from daft import resource_request
from daft.api_annotations import DataframePublicAPI
from daft.context import get_context
from daft.dataframe.preview import DataFramePreview
from daft.datasources import (
CSVSourceInfo,
JSONSourceInfo,
ParquetSourceInfo,
SourceInfo,
StorageType,
)
from daft.errors import ExpressionTypeError
from daft.execution.operators import ExpressionType
from daft.expressions import Expression, col
from daft.filesystem import get_filesystem_from_path
from daft.logical import logical_plan
from daft.logical.schema import ExpressionList
from daft.runners.partitioning import (
PartitionCacheEntry,
PartitionSet,
vPartition,
vPartitionParseCSVOptions,
vPartitionReadOptions,
vPartitionSchemaInferenceOptions,
)
from daft.runners.pyrunner import LocalPartitionSet
from daft.viz import DataFrameDisplay
if TYPE_CHECKING:
from ray.data.dataset import Dataset as RayDataset
from daft.logical.field import Field
from daft.logical.schema import Schema
UDFReturnType = TypeVar("UDFReturnType", covariant=True)
ColumnInputType = Union[Expression, str]
def _get_tabular_files_scan(
path: str, get_schema: Callable[[str], Schema], source_info: SourceInfo
) -> logical_plan.TabularFilesScan:
"""Returns a TabularFilesScan LogicalPlan for a given glob filepath."""
# Glob the path and return as a DataFrame with a column containing the filepaths
partition_set_factory = get_context().runner().partition_set_factory()
partition_set, filepaths_schema = partition_set_factory.glob_paths_details(path)
cache_entry = get_context().runner().put_partition_set_into_cache(partition_set)
filepath_plan = logical_plan.InMemoryScan(
cache_entry=cache_entry,
schema=filepaths_schema,
partition_spec=logical_plan.PartitionSpec(logical_plan.PartitionScheme.UNKNOWN, partition_set.num_partitions()),
)
filepath_df = DataFrame(filepath_plan)
# Sample the first 10 filepaths and infer the schema
schema_df = filepath_df.limit(10).select(
col(partition_set_factory.FS_LISTING_PATH_COLUMN_NAME)
.apply(get_schema, return_type=ExpressionList)
.alias("schema")
)
schema_df.collect()
schema_result = schema_df._result
assert schema_result is not None
sampled_schemas = schema_result.to_pydict()["schema"]
# TODO: infer schema from all sampled schemas instead of just taking the first one
schema = sampled_schemas[0]
# Return a TabularFilesScan node that will scan from the globbed filepaths filepaths
return logical_plan.TabularFilesScan(
schema=schema,
predicate=None,
columns=None,
source_info=source_info,
filepaths_child=filepath_plan,
filepaths_column_name=partition_set_factory.FS_LISTING_PATH_COLUMN_NAME,
# Hardcoded for now.
num_partitions=len(partition_set),
)
class DataFrame:
"""A Daft DataFrame is a table of data. It has columns, where each column has a type and the same
number of items (rows) as all other columns.
"""
def __init__(self, plan: logical_plan.LogicalPlan) -> None:
"""Constructs a DataFrame according to a given LogicalPlan. Users are expected instead to call
the classmethods on DataFrame to create a DataFrame.
Args:
plan: LogicalPlan describing the steps required to arrive at this DataFrame
"""
if not isinstance(plan, logical_plan.LogicalPlan):
if isinstance(plan, dict):
raise ValueError(
f"DataFrames should be constructed with a dictionary of columns using `DataFrame.from_pydict`"
)
if isinstance(plan, list):
raise ValueError(
f"DataFrames should be constructed with a list of dictionaries using `DataFrame.from_pylist`"
)
raise ValueError(f"Expected DataFrame to be constructed with a LogicalPlan, received: {plan}")
self.__plan = plan
self._result_cache: PartitionCacheEntry | None = None
self._preview = DataFramePreview(preview_partition=None, dataframe_num_rows=None)
@property
def _plan(self) -> logical_plan.LogicalPlan:
if self._result_cache is None:
return self.__plan
else:
return logical_plan.InMemoryScan(self._result_cache, self.__plan.schema(), self.__plan.partition_spec())
@property
def _result(self) -> PartitionSet | None:
if self._result_cache is None:
return None
else:
return self._result_cache.value
def plan(self) -> logical_plan.LogicalPlan:
"""Returns `LogicalPlan` that will be executed to compute the result of this DataFrame.
Returns:
logical_plan.LogicalPlan: LogicalPlan to compute this DataFrame.
"""
return self.__plan
@DataframePublicAPI
def explain(self, show_optimized: bool = False) -> None:
"""Prints the LogicalPlan that will be executed to produce this DataFrame.
Defaults to showing the unoptimized plan. Use `show_optimized` to show the optimized one.
Args:
show_optimized (bool): shows the optimized QueryPlan instead of the unoptimized one.
"""
if self._result_cache is not None:
print("Result is cached and will skip computation\n")
print(self._plan.pretty_print())
print("However here is the logical plan used to produce this result:\n")
plan = self.__plan
if show_optimized:
plan = get_context().runner().optimize(plan)
print(plan.pretty_print())
def num_partitions(self) -> int:
return self.__plan.num_partitions()
@DataframePublicAPI
def schema(self) -> Schema:
"""Returns the Schema of the DataFrame, which provides information about each column
Returns:
Schema: schema of the DataFrame
"""
return self.__plan.schema()
@property
def column_names(self) -> list[str]:
"""Returns column names of DataFrame as a list of strings.
Returns:
List[str]: Column names of this DataFrame.
"""
return self.__plan.schema().column_names()
@property
def columns(self) -> list[Expression]:
"""Returns column of DataFrame as a list of Expressions.
Returns:
List[Expression]: Columns of this DataFrame.
"""
return [expr.to_column_expression() for expr in self.__plan.schema()]
@DataframePublicAPI
def show(self, n: int | None = None) -> DataFrameDisplay:
"""Executes enough of the DataFrame in order to display the first ``n`` rows
.. NOTE::
This call is **blocking** and will execute the DataFrame when called
Args:
n: number of rows to show. Defaults to None which indicates showing the entire Dataframe.
Returns:
DataFrameDisplay: object that has a rich tabular display
"""
df = self
if n is not None:
df = df.limit(n)
df.collect(num_preview_rows=n)
result = df._result
assert result is not None
# If showing all rows, then we can use the resulting DataFramePreview's dataframe_num_rows since no limit was applied
dataframe_num_rows = df._preview.dataframe_num_rows if n is None else None
preview = DataFramePreview(
preview_partition=df._preview.preview_partition,
dataframe_num_rows=dataframe_num_rows,
)
return DataFrameDisplay(preview, df.schema())
@DataframePublicAPI
def __repr__(self) -> str:
display = DataFrameDisplay(self._preview, self.schema())
return display.__repr__()
@DataframePublicAPI
def _repr_html_(self) -> str:
display = DataFrameDisplay(self._preview, self.schema())
return display._repr_html_()
###
# Creation methods
###
@classmethod
@DataframePublicAPI
def from_pylist(cls, data: list[dict[str, Any]]) -> DataFrame:
"""Creates a DataFrame from a list of dictionaries
Example:
>>> df = DataFrame.from_pylist([{"foo": 1}, {"foo": 2}])
Args:
data: list of dictionaries, where each key is a column name
Returns:
DataFrame: DataFrame created from list of dictionaries
"""
headers: set[str] = set()
for row in data:
if not isinstance(row, dict):
raise ValueError(f"Expected list of dictionaries of {{column_name: value}}, received: {type(row)}")
headers.update(row.keys())
return cls.from_pydict(data={header: [row.get(header, None) for row in data] for header in headers})
@classmethod
@DataframePublicAPI
def from_pydict(cls, data: dict[str, list]) -> DataFrame:
"""Creates a DataFrame from a Python dictionary
Example:
>>> df = DataFrame.from_pydict({"foo": [1, 2]})
Args:
data: Key -> Sequence[item] of data. Each Key is created as a column, and must have a value that is
a Python list. Values must be equal in length across all keys.
Returns:
DataFrame: DataFrame created from dictionary of columns
"""
column_lengths = {key: len(data[key]) for key in data}
if len(set(column_lengths.values())) > 1:
raise ValueError(
f"Expected all columns to be of the same length, but received columns with lengths: {column_lengths}"
)
for header in data:
if not isinstance(data[header], list):
raise ValueError(
f"Expected all columns to be of type list, but received {type(data[header])} for {header}"
)
column_types: dict[str, ExpressionType] = {}
for header in data:
found_types = {type(o) for o in data[header]} - {type(None)}
if len(found_types) == 0:
column_types[header] = ExpressionType.null()
elif len(found_types) == 1:
column_types[header] = ExpressionType.from_py_type(found_types.pop())
elif found_types == {int, float}:
column_types[header] = ExpressionType.float()
else:
column_types[header] = ExpressionType.python_object()
schema = Schema([Field(header, expr_type) for header, expr_type in column_types.items()])
data_vpartition = vPartition.from_pydict(
data={header: arr for header, arr in data.items()}, schema=schema, partition_id=0
)
result_pset = LocalPartitionSet({0: data_vpartition})
cache_entry = get_context().runner().put_partition_set_into_cache(result_pset)
plan = logical_plan.InMemoryScan(
cache_entry=cache_entry,
schema=schema,
)
return cls(plan)
@classmethod
@DataframePublicAPI
def from_json(cls, *args, **kwargs) -> DataFrame:
warnings.warn(f"DataFrame.from_json will be deprecated in 0.1.0 in favor of DataFrame.read_json")
return cls.read_json(*args, **kwargs)
@classmethod
@DataframePublicAPI
def read_json(
cls,
path: str,
) -> DataFrame:
"""Creates a DataFrame from line-delimited JSON file(s)
Example:
>>> df = DataFrame.read_json("/path/to/file.json")
>>> df = DataFrame.read_json("/path/to/directory")
>>> df = DataFrame.read_json("/path/to/files-*.json")
>>> df = DataFrame.read_json("s3://path/to/files-*.json")
Args:
path (str): Path to JSON files (allows for wildcards)
returns:
DataFrame: parsed DataFrame
"""
def get_schema(filepath: str) -> Schema:
return vPartition.from_json(
filepath,
partition_id=0,
schema_options=vPartitionSchemaInferenceOptions(
schema=None,
inference_column_names=None, # has no effect on inferring schema from JSON
),
read_options=vPartitionReadOptions(
num_rows=100, # sample 100 rows for inferring schema
column_names=None, # read all columns
),
).get_schema()
plan = _get_tabular_files_scan(
path,
get_schema,
JSONSourceInfo(),
)
return cls(plan)
@classmethod
@DataframePublicAPI
def from_csv(cls, *args, **kwargs) -> DataFrame:
warnings.warn(f"DataFrame.from_csv will be deprecated in 0.1.0 in favor of DataFrame.read_csv")
return cls.read_csv(*args, **kwargs)
@classmethod
@DataframePublicAPI
def read_csv(
cls,
path: str,
has_headers: bool = True,
column_names: list[str] | None = None,
delimiter: str = ",",
) -> DataFrame:
"""Creates a DataFrame from CSV file(s)
Example:
>>> df = DataFrame.read_csv("/path/to/file.csv")
>>> df = DataFrame.read_csv("/path/to/directory")
>>> df = DataFrame.read_csv("/path/to/files-*.csv")
>>> df = DataFrame.read_csv("s3://path/to/files-*.csv")
Args:
path (str): Path to CSV (allows for wildcards)
has_headers (bool): Whether the CSV has a header or not, defaults to True
column_names (Optional[List[str]]): Custom column names to assign to the DataFrame, defaults to None
delimiter (Str): Delimiter used in the CSV, defaults to ","
returns:
DataFrame: parsed DataFrame
"""
def get_schema(filepath: str) -> Schema:
return vPartition.from_csv(
path=filepath,
partition_id=0,
csv_options=vPartitionParseCSVOptions(
delimiter=delimiter,
has_headers=has_headers,
skip_rows_before_header=0,
skip_rows_after_header=0,
),
schema_options=vPartitionSchemaInferenceOptions(
schema=None,
inference_column_names=column_names, # pass in user-provided column names
),
read_options=vPartitionReadOptions(
num_rows=100, # sample 100 rows for schema inference
column_names=None, # read all columns
),
).get_schema()
plan = _get_tabular_files_scan(
path,
get_schema,
CSVSourceInfo(
delimiter=delimiter,
has_headers=has_headers,
),
)
return cls(plan)
@classmethod
@DataframePublicAPI
def from_parquet(cls, *args, **kwargs) -> DataFrame:
warnings.warn(f"DataFrame.from_parquet will be deprecated in 0.1.0 in favor of DataFrame.read_parquet")
return cls.read_parquet(*args, **kwargs)
@classmethod
@DataframePublicAPI
def read_parquet(cls, path: str) -> DataFrame:
"""Creates a DataFrame from Parquet file(s)
Example:
>>> df = DataFrame.read_parquet("/path/to/file.parquet")
>>> df = DataFrame.read_parquet("/path/to/directory")
>>> df = DataFrame.read_parquet("/path/to/files-*.parquet")
>>> df = DataFrame.read_parquet("s3://path/to/files-*.parquet")
Args:
path (str): Path to Parquet file (allows for wildcards)
returns:
DataFrame: parsed DataFrame
"""
def get_schema(filepath: str) -> Schema:
return vPartition.from_parquet(
filepath,
partition_id=0,
schema_options=vPartitionSchemaInferenceOptions(
schema=None,
inference_column_names=None, # has no effect on schema inferencing Parquet
),
read_options=vPartitionReadOptions(
num_rows=0, # sample 0 rows since Parquet has metadata
column_names=None, # read all columns
),
).get_schema()
plan = _get_tabular_files_scan(
path,
get_schema,
ParquetSourceInfo(),
)
return cls(plan)
@classmethod
@DataframePublicAPI
def from_files(cls, path: str) -> DataFrame:
"""Creates a DataFrame of file paths and other metadata from a glob path
Example:
>>> df = DataFrame.from_files("/path/to/files/*.jpeg")
Args:
path (str): path to files on disk (allows wildcards)
Returns:
DataFrame: DataFrame containing the path to each file as a row, along with other metadata
parsed from the provided filesystem
"""
warnings.warn(
f"DataFrame.from_files will be deprecated in 0.1.0 in favor of DataFrame.from_glob_path, which presents a more predictable set of columns for each backend and runs the file globbing on the runner instead of the driver"
)
fs = get_filesystem_from_path(path)
file_details = fs.glob(path, detail=True)
return cls.from_pylist(list(file_details.values()))
@classmethod
@DataframePublicAPI
def from_glob_path(cls, path: str) -> DataFrame:
"""Creates a DataFrame of file paths and other metadata from a glob path
This method supports wildcards:
1. "*" matches any number of any characters including none
2. "?" matches any single character
3. "[...]" matches any single character in the brackets
4. "**" recursively matches any number of layers of directories
The returned DataFrame will have the following columns:
1. path: the path to the file/directory
2. size: size of the object in bytes
3. type: either "file" or "directory"
Example:
>>> df = DataFrame.from_glob_path("/path/to/files/*.jpeg")
>>> df = DataFrame.from_glob_path("/path/to/files/**/*.jpeg")
>>> df = DataFrame.from_glob_path("/path/to/files/**/image-?.jpeg")
Args:
path (str): path to files on disk (allows wildcards)
Returns:
DataFrame: DataFrame containing the path to each file as a row, along with other metadata
parsed from the provided filesystem
"""
partition_set_factory = get_context().runner().partition_set_factory()
partition_set, filepaths_schema = partition_set_factory.glob_paths_details(path)
cache_entry = get_context().runner().put_partition_set_into_cache(partition_set)
filepath_plan = logical_plan.InMemoryScan(
cache_entry=cache_entry,
schema=filepaths_schema,
partition_spec=logical_plan.PartitionSpec(
logical_plan.PartitionScheme.UNKNOWN, partition_set.num_partitions()
),
)
return cls(filepath_plan)
###
# Write methods
###
@DataframePublicAPI
def write_parquet(
self, root_dir: str, compression: str = "snappy", partition_cols: list[ColumnInputType] | None = None
) -> DataFrame:
"""Writes the DataFrame as parquet files, returning a new DataFrame with paths to the files that were written
Files will be written to ``<root_dir>/*`` with randomly generated UUIDs as the file names.
Currently generates a parquet file per partition unless `partition_cols` are used, then the number of files can equal the number of partitions times the number of values of partition col.
.. NOTE::
This call is **blocking** and will execute the DataFrame when called
Args:
root_dir (str): root file path to write parquet files to.
compression (str, optional): compression algorithm. Defaults to "snappy".
partition_cols (Optional[List[ColumnInputType]], optional): How to subpartition each partition further. Currently only supports Column Expressions with any calls. Defaults to None.
Returns:
DataFrame: The filenames that were written out as strings.
.. NOTE::
This call is **blocking** and will execute the DataFrame when called
"""
cols: ExpressionList | None = None
if partition_cols is not None:
cols = self.__column_input_to_expression(tuple(partition_cols))
for c in cols:
assert c.is_column(), "we cant support non Column Expressions for partition writing"
df = self.repartition(self.num_partitions(), *cols)
else:
df = self
plan = logical_plan.FileWrite(
df._plan,
root_dir=root_dir,
partition_cols=cols,
storage_type=StorageType.PARQUET,
compression=compression,
)
# Block and write, then retrieve data and return a new disconnected DataFrame
write_df = DataFrame(plan)
write_df.collect()
assert write_df._result is not None
return DataFrame(write_df._plan)
@DataframePublicAPI
def write_csv(self, root_dir: str, partition_cols: list[ColumnInputType] | None = None) -> DataFrame:
"""Writes the DataFrame as CSV files, returning a new DataFrame with paths to the files that were written
Files will be written to ``<root_dir>/*`` with randomly generated UUIDs as the file names.
Currently generates a csv file per partition unless `partition_cols` are used, then the number of files can equal the number of partitions times the number of values of partition col.
.. NOTE::
This call is **blocking** and will execute the DataFrame when called
Args:
root_dir (str): root file path to write parquet files to.
compression (str, optional): compression algorithm. Defaults to "snappy".
partition_cols (Optional[List[ColumnInputType]], optional): How to subpartition each partition further. Currently only supports Column Expressions with any calls. Defaults to None.
Returns:
DataFrame: The filenames that were written out as strings.
"""
cols: ExpressionList | None = None
if partition_cols is not None:
cols = self.__column_input_to_expression(tuple(partition_cols))
for c in cols:
assert c.is_column(), "we cant support non Column Expressions for partition writing"
df = self.repartition(self.num_partitions(), *cols)
else:
df = self
plan = logical_plan.FileWrite(
df._plan,
root_dir=root_dir,
partition_cols=cols,
storage_type=StorageType.CSV,
)
# Block and write, then retrieve data and return a new disconnected DataFrame
write_df = DataFrame(plan)
write_df.collect()
assert write_df._result is not None
return DataFrame(write_df._plan)
###
# DataFrame operations
###
def __column_input_to_expression(self, columns: Iterable[ColumnInputType]) -> ExpressionList:
expressions = [col(c) if isinstance(c, str) else c for c in columns]
return ExpressionList(expressions)
def __getitem__(self, item: slice | int | str | Iterable[str | int]) -> Expression | DataFrame:
"""Gets a column from the DataFrame as an Expression (``df["mycol"]``)"""
result: Expression | None
if isinstance(item, int):
schema = self._plan.schema()
if item < -len(schema) or item >= len(schema):
raise ValueError(f"{item} out of bounds for {schema}")
result = schema.to_column_expressions().exprs[item]
assert result is not None
return result
elif isinstance(item, str):
schema = self._plan.schema()
result = schema[item].to_column_expression()
return result
elif isinstance(item, Iterable):
schema = self._plan.schema()
col_exprs = self._plan.schema().to_column_expressions()
columns = []
for it in item:
if isinstance(it, str):
result = schema[it].to_column_expression()
if result is None:
raise ValueError(f"{it} not found in DataFrame schema {schema}")
columns.append(result)
elif isinstance(it, int):
if it < -len(schema) or it >= len(schema):
raise ValueError(f"{it} out of bounds for {schema}")
result = col_exprs.exprs[it]
assert result is not None
columns.append(result)
else:
raise ValueError(f"unknown indexing type: {type(it)}")
return self.select(*columns)
elif isinstance(item, slice):
schema = self._plan.schema()
columns_exprs: ExpressionList = schema.to_column_expressions()
selected_columns = columns_exprs.exprs[item]
return self.select(*selected_columns)
else:
raise ValueError(f"unknown indexing type: {type(item)}")
@DataframePublicAPI
def select(self, *columns: ColumnInputType) -> DataFrame:
"""Creates a new DataFrame from the provided expressions, similar to a SQL ``SELECT``
Example:
>>> # names of columns as strings
>>> df = df.select('x', 'y')
>>>
>>> # names of columns as expressions
>>> df = df.select(col('x'), col('y'))
>>>
>>> # call expressions
>>> df = df.select(col('x') * col('y'))
>>>
>>> # any mix of the above
>>> df = df.select('x', col('y'), col('z') + 1)
Args:
*columns (Union[str, Expression]): columns to select from the current DataFrame
Returns:
DataFrame: new DataFrame that will select the passed in columns
"""
assert len(columns) > 0
projection = logical_plan.Projection(
self._plan, self.__column_input_to_expression(columns), custom_resource_request=None
)
return DataFrame(projection)
@DataframePublicAPI
def distinct(self) -> DataFrame:
"""Computes unique rows, dropping duplicates
Example:
>>> unique_df = df.distinct()
Returns:
DataFrame: DataFrame that has only unique rows.
"""
all_exprs = self._plan.schema().to_column_expressions()
plan: logical_plan.LogicalPlan = logical_plan.LocalDistinct(self._plan, all_exprs)
if self.num_partitions() > 1:
plan = logical_plan.Repartition(
plan,
partition_by=all_exprs,
num_partitions=self.num_partitions(),
scheme=logical_plan.PartitionScheme.HASH,
)
plan = logical_plan.LocalDistinct(plan, all_exprs)
return DataFrame(plan)
@DataframePublicAPI
def exclude(self, *names: str) -> DataFrame:
"""Drops columns from the current DataFrame by name
This is equivalent of performing a select with all the columns but the ones excluded.
Example:
>>> df_without_x = df.exclude('x')
Args:
*names (str): names to exclude
Returns:
DataFrame: DataFrame with some columns excluded.
"""
names_to_skip = set(names)
el = ExpressionList([col(e.name) for e in self._plan.schema() if e.name not in names_to_skip])
return DataFrame(logical_plan.Projection(self._plan, el, custom_resource_request=None))
@DataframePublicAPI
def where(self, predicate: Expression) -> DataFrame:
"""Filters rows via a predicate expression, similar to SQL ``WHERE``.
Example:
>>> filtered_df = df.where((col('x') < 10) & (col('y') == 10))
Args:
predicate (Expression): expression that keeps row if evaluates to True.
Returns:
DataFrame: Filtered DataFrame.
"""
plan = logical_plan.Filter(self._plan, ExpressionList([predicate]))
return DataFrame(plan)
@DataframePublicAPI
def with_column(
self, column_name: str, expr: Expression, resource_request: resource_request.ResourceRequest | None = None
) -> DataFrame:
"""Adds a column to the current DataFrame with an Expression, equivalent to a ``select``
with all current columns and the new one
Example:
>>> new_df = df.with_column('x+1', col('x') + 1)
Args:
column_name (str): name of new column
expr (Expression): expression of the new column.
resource_request (resource_request.ResourceRequest): a custom resource request for the execution of this operation
Returns:
DataFrame: DataFrame with new column.
"""
prev_schema_as_cols = self._plan.schema().to_column_expressions()
projection = logical_plan.Projection(
self._plan,
prev_schema_as_cols.union(ExpressionList([expr.alias(column_name)]), other_override=True),
custom_resource_request=resource_request,
)
return DataFrame(projection)
@DataframePublicAPI
def sort(self, by: ColumnInputType | list[ColumnInputType], desc: bool | list[bool] = False) -> DataFrame:
"""Sorts DataFrame globally
Example:
>>> sorted_df = df.sort(col('x') + col('y'))
>>> sorted_df = df.sort([col('x'), col('y')], desc=[False, True])
>>> sorted_df = df.sort(['z', col('x'), col('y')], desc=[True, False, True])
Note:
* Since this a global sort, this requires an expensive repartition which can be quite slow.
* Supports multicolumn sorts and can have unique `descending` flag per column.
Args:
column (Union[ColumnInputType, List[ColumnInputType]]): column to sort by. Can be `str` or expression as well as a list of either.
desc (Union[bool, List[bool]), optional): Sort by descending order. Defaults to False.
Returns:
DataFrame: Sorted DataFrame.
"""
if not isinstance(by, list):
by = [
by,
]
sort = logical_plan.Sort(self._plan, self.__column_input_to_expression(by), descending=desc)
return DataFrame(sort)
@DataframePublicAPI
def limit(self, num: int) -> DataFrame:
"""Limits the rows in the DataFrame to the first ``N`` rows, similar to a SQL ``LIMIT``
Example:
>>> df_limited = df.limit(10) # returns 10 rows
Args:
num (int): maximum rows to allow.
Returns:
DataFrame: Limited DataFrame
"""
local_limit = logical_plan.LocalLimit(self._plan, num=num)
global_limit = logical_plan.GlobalLimit(local_limit, num=num)
return DataFrame(global_limit)
@DataframePublicAPI
def count_rows(self) -> int:
"""Executes the Dataframe to count the number of rows.
Returns:
int: count of the number of rows in this DataFrame.
"""
local_count_op = logical_plan.LocalCount(self._plan)
coalease_op = logical_plan.Coalesce(local_count_op, 1)
local_sum_op = logical_plan.LocalAggregate(coalease_op, [(Expression._sum(col("count")), "sum")])
num_rows = DataFrame(local_sum_op).to_pydict()["count"][0]
return num_rows
@DataframePublicAPI
def repartition(self, num: int, *partition_by: ColumnInputType) -> DataFrame:
"""Repartitions DataFrame to ``num`` partitions
If columns are passed in, then DataFrame will be repartitioned by those, otherwise
random repartitioning will occur.
Example:
>>> random_repart_df = df.repartition(4)
>>> part_by_df = df.repartition(4, 'x', col('y') + 1)
Args:
num (int): number of target partitions.
*partition_by (Union[str, Expression]): optional columns to partition by.
Returns:
DataFrame: Repartitioned DataFrame.
"""
if len(partition_by) == 0:
scheme = logical_plan.PartitionScheme.RANDOM
exprs: ExpressionList = ExpressionList([])
else:
assert len(partition_by) == 1
scheme = logical_plan.PartitionScheme.HASH
exprs = self.__column_input_to_expression(partition_by)
repartition_op = logical_plan.Repartition(self._plan, num_partitions=num, partition_by=exprs, scheme=scheme)
return DataFrame(repartition_op)
@DataframePublicAPI
def join(
self,
other: DataFrame,
on: list[ColumnInputType] | ColumnInputType | None = None,
left_on: list[ColumnInputType] | ColumnInputType | None = None,
right_on: list[ColumnInputType] | ColumnInputType | None = None,
how: str = "inner",
) -> DataFrame:
"""Column-wise join of the current DataFrame with an ``other`` DataFrame, similar to a SQL ``JOIN``
.. NOTE::
Although self joins are supported, we currently duplicate the logical plan for the right side
and recompute the entire tree. Caching for this is on the roadmap.
Args:
other (DataFrame): the right DataFrame to join on.
on (Optional[Union[List[ColumnInputType], ColumnInputType]], optional): key or keys to join on [use if the keys on the left and right side match.]. Defaults to None.
left_on (Optional[Union[List[ColumnInputType], ColumnInputType]], optional): key or keys to join on left DataFrame.. Defaults to None.
right_on (Optional[Union[List[ColumnInputType], ColumnInputType]], optional): key or keys to join on right DataFrame. Defaults to None.
how (str, optional): what type of join to performing, currently only `inner` is supported. Defaults to "inner".
Raises:
ValueError: if `on` is passed in and `left_on` or `right_on` is not None.
ValueError: if `on` is None but both `left_on` and `right_on` are not defined.
Returns:
DataFrame: Joined DataFrame.
"""
if on is None:
if left_on is None or right_on is None:
raise ValueError("If `on` is None then both `left_on` and `right_on` must not be None")
else:
if left_on is not None or right_on is not None:
raise ValueError("If `on` is not None then both `left_on` and `right_on` must be None")
left_on = on
right_on = on
assert how == "inner", "only inner joins are currently supported"
left_exprs = self.__column_input_to_expression(tuple(left_on) if isinstance(left_on, list) else (left_on,))
right_exprs = self.__column_input_to_expression(tuple(right_on) if isinstance(right_on, list) else (right_on,))
join_op = logical_plan.Join(
self._plan, other._plan, left_on=left_exprs, right_on=right_exprs, how=logical_plan.JoinType.INNER
)
return DataFrame(join_op)
@DataframePublicAPI
def explode(self, *columns: ColumnInputType) -> DataFrame:
"""Explodes a List column, where every element in each row's List becomes its own row, and all
other columns in the DataFrame are duplicated across rows
If multiple columns are specified, each row must contain the same number of
items in each specified column.
Exploding Null values or empty lists will create a single Null entry (see example below).
Example:
>>> df = DataFrame.from_pydict({
>>> "x": [[1], [2, 3]],
>>> "y": [["a"], ["b", "c"]],
>>> "z": [1.0, 2.0],
>>> ]})
>>>
>>> df.explode(col("x"), col("y"))
>>>
>>> # +------+-----------+-----+ +------+------+-----+
>>> # | x | y | z | | x | y | z |
>>> # +------+-----------+-----+ +------+------+-----+
>>> # |[1] | ["a"] | 1.0 | | 1 | "a" | 1.0 |
>>> # +------+-----------+-----+ -> +------+------+-----+
>>> # |[2, 3]| ["b", "c"]| 2.0 | | 2 | "b" | 2.0 |
>>> # +------+-----------+-----+ +------+------+-----+
>>> # |[] | [] | 3.0 | | 3 | "c" | 2.0 |
>>> # +------+-----------+-----+ +------+------+-----+
>>> # |None | None | 4.0 | | None | None | 3.0 |
>>> # +------+-----------+-----+ +------+------+-----+
>>> # | None | None | 4.0 |
>>> # +------+------+-----+
Args:
*columns (ColumnInputType): columns to explode
Returns:
DataFrame: DataFrame with exploded column
"""
if len(columns) < 1:
raise ValueError("At least one column to explode must be specified")
exprs_to_explode = self.__column_input_to_expression(columns)
explode_op = logical_plan.Explode(
self._plan,
ExpressionList([e._explode() for e in exprs_to_explode]),
)
return DataFrame(explode_op)
def _agg(self, to_agg: list[tuple[ColumnInputType, str]], group_by: ExpressionList | None = None) -> DataFrame:
assert len(to_agg) > 0, "no columns to aggregate."
exprs_to_agg = self.__column_input_to_expression(tuple(e for e, _ in to_agg))
ops = [op for _, op in to_agg]
function_lookup = {
"sum": Expression._sum,
"count": Expression._count,
"mean": Expression._mean,
"list": Expression._list,
"concat": Expression._concat,
"min": Expression._min,
"max": Expression._max,
}
if self.num_partitions() == 1:
agg_exprs = []
for e, op_name in zip(exprs_to_agg, ops):
assert op_name in function_lookup
agg_exprs.append((function_lookup[op_name](e).alias(e.name()), op_name))
plan = logical_plan.LocalAggregate(self._plan, agg=agg_exprs, group_by=group_by)
return DataFrame(plan)
intermediate_ops = {
"sum": ("sum",),
"list": ("list",),
"count": ("count",),
"mean": ("sum", "count"),
"min": ("min",),
"max": ("max",),
}
reduction_ops = {
"sum": ("sum",),
"list": ("concat",),
"count": ("sum",),
"mean": ("sum", "sum"),
"min": ("min",),
"max": ("max",),