forked from modin-project/modin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_compiler.py
4584 lines (4048 loc) · 176 KB
/
query_compiler.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
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
"""
Module contains ``PandasQueryCompiler`` class.
``PandasQueryCompiler`` is responsible for compiling efficient DataFrame algebra
queries for the ``PandasDataframe``.
"""
import ast
import hashlib
import re
import warnings
from collections.abc import Iterable
from typing import Hashable, List
import numpy as np
import pandas
from pandas._libs import lib
from pandas.api.types import is_scalar
from pandas.core.apply import reconstruct_func
from pandas.core.common import is_bool_indexer
from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.common import (
is_bool_dtype,
is_datetime64_any_dtype,
is_list_like,
is_numeric_dtype,
)
from pandas.core.groupby.base import transformation_kernels
from pandas.core.indexes.api import ensure_index_from_sequences
from pandas.core.indexing import check_bool_indexer
from pandas.errors import DataError
from modin.config import CpuCount, RangePartitioning, RangePartitioningGroupby
from modin.core.dataframe.algebra import (
Binary,
Fold,
GroupByReduce,
Map,
Reduce,
TreeReduce,
)
from modin.core.dataframe.algebra.default2pandas.groupby import (
GroupBy,
GroupByDefault,
SeriesGroupByDefault,
)
from modin.core.dataframe.pandas.metadata import (
DtypesDescriptor,
ModinDtypes,
ModinIndex,
extract_dtype,
)
from modin.core.storage_formats.base.query_compiler import BaseQueryCompiler
from modin.error_message import ErrorMessage
from modin.logging import get_logger
from modin.utils import (
MODIN_UNNAMED_SERIES_LABEL,
_inherit_docstrings,
hashable,
try_cast_to_pandas,
wrap_udf_function,
)
from .aggregations import CorrCovBuilder
from .groupby import GroupbyReduceImpl, PivotTableImpl
from .merge import MergeImpl
from .utils import get_group_names, merge_partitioning
def _get_axis(axis):
"""
Build index labels getter of the specified axis.
Parameters
----------
axis : {0, 1}
Axis to get labels from. 0 is for index and 1 is for column.
Returns
-------
callable(PandasQueryCompiler) -> pandas.Index
"""
if axis == 0:
return lambda self: self._modin_frame.index
else:
return lambda self: self._modin_frame.columns
def _set_axis(axis):
"""
Build index labels setter of the specified axis.
Parameters
----------
axis : {0, 1}
Axis to set labels on. 0 is for index and 1 is for column.
Returns
-------
callable(PandasQueryCompiler)
"""
if axis == 0:
def set_axis(self, idx):
self._modin_frame.index = idx
else:
def set_axis(self, cols):
self._modin_frame.columns = cols
return set_axis
def _str_map(func_name):
"""
Build function that calls specified string function on frames ``str`` accessor.
Parameters
----------
func_name : str
String function name to execute on ``str`` accessor.
Returns
-------
callable(pandas.DataFrame, *args, **kwargs) -> pandas.DataFrame
"""
def str_op_builder(df, *args, **kwargs):
"""Apply specified function against `str` accessor of the passed frame."""
str_s = df.squeeze(axis=1).str
res = getattr(pandas.Series.str, func_name)(str_s, *args, **kwargs)
if hasattr(res, "to_frame"):
res = res.to_frame()
return res
return str_op_builder
def _dt_prop_map(property_name):
"""
Build function that access specified property of the ``dt`` property of the passed frame.
Parameters
----------
property_name : str
Date-time property name to access.
Returns
-------
callable(pandas.DataFrame, *args, **kwargs) -> pandas.DataFrame
Function to be applied in the partitions.
Notes
-----
This applies non-callable properties of ``Series.dt``.
"""
def dt_op_builder(df, *args, **kwargs):
"""Access specified date-time property of the passed frame."""
squeezed_df = df.squeeze(axis=1)
if isinstance(squeezed_df, pandas.DataFrame) and len(squeezed_df.columns) == 0:
return squeezed_df
assert isinstance(squeezed_df, pandas.Series)
prop_val = getattr(squeezed_df.dt, property_name)
if isinstance(prop_val, pandas.Series):
return prop_val.to_frame()
elif isinstance(prop_val, pandas.DataFrame):
return prop_val
else:
return pandas.DataFrame([prop_val])
return dt_op_builder
def _dt_func_map(func_name):
"""
Build function that apply specified method against ``dt`` property of the passed frame.
Parameters
----------
func_name : str
Date-time function name to apply.
Returns
-------
callable(pandas.DataFrame, *args, **kwargs) -> pandas.DataFrame
Function to be applied in the partitions.
Notes
-----
This applies callable methods of ``Series.dt``.
"""
def dt_op_builder(df, *args, **kwargs):
"""Apply specified function against ``dt`` accessor of the passed frame."""
dt_s = df.squeeze(axis=1).dt
dt_func_result = getattr(pandas.Series.dt, func_name)(dt_s, *args, **kwargs)
# If we don't specify the dtype for the frame, the frame might get the
# wrong dtype, e.g. for to_pydatetime in https://github.com/modin-project/modin/issues/4436
return pandas.DataFrame(dt_func_result, dtype=dt_func_result.dtype)
return dt_op_builder
def copy_df_for_func(func, display_name: str = None):
"""
Build function that execute specified `func` against passed frame inplace.
Built function copies passed frame, applies `func` to the copy and returns
the modified frame.
Parameters
----------
func : callable(pandas.DataFrame)
The function, usually updates a dataframe inplace.
display_name : str, optional
The function's name, which is displayed by progress bar.
Returns
-------
callable(pandas.DataFrame)
A callable function to be applied in the partitions.
"""
def caller(df, *args, **kwargs):
"""Apply specified function the passed frame inplace."""
df = df.copy()
func(df, *args, **kwargs)
return df
if display_name is not None:
caller.__name__ = display_name
return caller
@_inherit_docstrings(BaseQueryCompiler)
class PandasQueryCompiler(BaseQueryCompiler):
"""
Query compiler for the pandas storage format.
This class translates common query compiler API into the DataFrame Algebra
queries, that is supposed to be executed by :py:class:`~modin.core.dataframe.pandas.dataframe.dataframe.PandasDataframe`.
Parameters
----------
modin_frame : PandasDataframe
Modin Frame to query with the compiled queries.
shape_hint : {"row", "column", None}, default: None
Shape hint for frames known to be a column or a row, otherwise None.
"""
def __init__(self, modin_frame, shape_hint=None):
self._modin_frame = modin_frame
self._shape_hint = shape_hint
@property
def lazy_execution(self):
"""
Whether underlying Modin frame should be executed in a lazy mode.
If True, such QueryCompiler will be handled differently at the front-end in order
to reduce triggering the computation as much as possible.
Returns
-------
bool
"""
frame = self._modin_frame
return not frame.has_materialized_index or not frame.has_materialized_columns
def finalize(self):
self._modin_frame.finalize()
def execute(self):
self.finalize()
self._modin_frame.wait_computations()
def to_pandas(self):
return self._modin_frame.to_pandas()
@classmethod
def from_pandas(cls, df, data_cls):
return cls(data_cls.from_pandas(df))
@classmethod
def from_arrow(cls, at, data_cls):
return cls(data_cls.from_arrow(at))
# Dataframe exchange protocol
def to_dataframe(self, nan_as_null: bool = False, allow_copy: bool = True):
return self._modin_frame.__dataframe__(
nan_as_null=nan_as_null, allow_copy=allow_copy
)
@classmethod
def from_dataframe(cls, df, data_cls):
return cls(data_cls.from_dataframe(df))
# END Dataframe exchange protocol
index = property(_get_axis(0), _set_axis(0))
columns = property(_get_axis(1), _set_axis(1))
@property
def dtypes(self):
return self._modin_frame.dtypes
def get_dtypes_set(self):
return self._modin_frame.get_dtypes_set()
# END Index, columns, and dtypes objects
# Metadata modification methods
def add_prefix(self, prefix, axis=1):
if axis == 1:
return self.__constructor__(
self._modin_frame.rename(new_col_labels=lambda x: f"{prefix}{x}")
)
else:
return self.__constructor__(
self._modin_frame.rename(new_row_labels=lambda x: f"{prefix}{x}")
)
def add_suffix(self, suffix, axis=1):
if axis == 1:
return self.__constructor__(
self._modin_frame.rename(new_col_labels=lambda x: f"{x}{suffix}")
)
else:
return self.__constructor__(
self._modin_frame.rename(new_row_labels=lambda x: f"{x}{suffix}")
)
# END Metadata modification methods
# Copy
# For copy, we don't want a situation where we modify the metadata of the
# copies if we end up modifying something here. We copy all of the metadata
# to prevent that.
def copy(self):
return self.__constructor__(self._modin_frame.copy(), self._shape_hint)
# END Copy
# Append/Concat/Join (Not Merge)
# The append/concat/join operations should ideally never trigger remote
# compute. These operations should only ever be manipulations of the
# metadata of the resulting object. It should just be a simple matter of
# appending the other object's blocks and adding np.nan columns for the new
# columns, if needed. If new columns are added, some compute may be
# required, though it can be delayed.
#
# Currently this computation is not delayed, and it may make a copy of the
# DataFrame in memory. This can be problematic and should be fixed in the
# future. TODO (devin-petersohn): Delay reindexing
def concat(self, axis, other, **kwargs):
if not isinstance(other, list):
other = [other]
assert all(
isinstance(o, type(self)) for o in other
), "Different Manager objects are being used. This is not allowed"
sort = kwargs.get("sort", None)
if sort is None:
sort = False
join = kwargs.get("join", "outer")
ignore_index = kwargs.get("ignore_index", False)
other_modin_frame = [o._modin_frame for o in other]
new_modin_frame = self._modin_frame.concat(axis, other_modin_frame, join, sort)
result = self.__constructor__(new_modin_frame)
if ignore_index:
if axis == 0:
return result.reset_index(drop=True)
else:
result.columns = pandas.RangeIndex(len(result.columns))
return result
return result
# END Append/Concat/Join
# Data Management Methods
def free(self):
# TODO create a way to clean up this object.
return
# END Data Management Methods
# To NumPy
def to_numpy(self, **kwargs):
return self._modin_frame.to_numpy(**kwargs)
# END To NumPy
# Binary operations (e.g. add, sub)
# These operations require two DataFrames and will change the shape of the
# data if the index objects don't match. An outer join + op is performed,
# such that columns/rows that don't have an index on the other DataFrame
# result in NaN values.
add = Binary.register(pandas.DataFrame.add, infer_dtypes="try_sample")
# 'combine' and 'combine_first' are working with UDFs, so it's better not so sample them
combine = Binary.register(pandas.DataFrame.combine, infer_dtypes="common_cast")
combine_first = Binary.register(
pandas.DataFrame.combine_first, infer_dtypes="common_cast"
)
eq = Binary.register(pandas.DataFrame.eq, infer_dtypes="bool")
equals = Binary.register(
lambda df, other: pandas.DataFrame([[df.equals(other)]]),
join_type=None,
labels="drop",
infer_dtypes="bool",
)
floordiv = Binary.register(pandas.DataFrame.floordiv, infer_dtypes="try_sample")
ge = Binary.register(pandas.DataFrame.ge, infer_dtypes="bool")
gt = Binary.register(pandas.DataFrame.gt, infer_dtypes="bool")
le = Binary.register(pandas.DataFrame.le, infer_dtypes="bool")
lt = Binary.register(pandas.DataFrame.lt, infer_dtypes="bool")
mod = Binary.register(pandas.DataFrame.mod, infer_dtypes="try_sample")
mul = Binary.register(pandas.DataFrame.mul, infer_dtypes="try_sample")
rmul = Binary.register(pandas.DataFrame.rmul, infer_dtypes="try_sample")
ne = Binary.register(pandas.DataFrame.ne, infer_dtypes="bool")
pow = Binary.register(pandas.DataFrame.pow, infer_dtypes="try_sample")
radd = Binary.register(pandas.DataFrame.radd, infer_dtypes="try_sample")
rfloordiv = Binary.register(pandas.DataFrame.rfloordiv, infer_dtypes="try_sample")
rmod = Binary.register(pandas.DataFrame.rmod, infer_dtypes="try_sample")
rpow = Binary.register(pandas.DataFrame.rpow, infer_dtypes="try_sample")
rsub = Binary.register(pandas.DataFrame.rsub, infer_dtypes="try_sample")
rtruediv = Binary.register(pandas.DataFrame.rtruediv, infer_dtypes="try_sample")
sub = Binary.register(pandas.DataFrame.sub, infer_dtypes="try_sample")
truediv = Binary.register(pandas.DataFrame.truediv, infer_dtypes="try_sample")
__and__ = Binary.register(pandas.DataFrame.__and__, infer_dtypes="bool")
__or__ = Binary.register(pandas.DataFrame.__or__, infer_dtypes="bool")
__rand__ = Binary.register(pandas.DataFrame.__rand__, infer_dtypes="bool")
__ror__ = Binary.register(pandas.DataFrame.__ror__, infer_dtypes="bool")
__rxor__ = Binary.register(pandas.DataFrame.__rxor__, infer_dtypes="bool")
__xor__ = Binary.register(pandas.DataFrame.__xor__, infer_dtypes="bool")
df_update = Binary.register(
copy_df_for_func(pandas.DataFrame.update, display_name="update"),
join_type="left",
)
series_update = Binary.register(
copy_df_for_func(
lambda x, y: pandas.Series.update(x.squeeze(axis=1), y.squeeze(axis=1)),
display_name="update",
),
join_type="left",
)
# Needed for numpy API
_logical_and = Binary.register(
lambda df, other, *args, **kwargs: pandas.DataFrame(
np.logical_and(df, other, *args, **kwargs)
),
infer_dtypes="bool",
)
_logical_or = Binary.register(
lambda df, other, *args, **kwargs: pandas.DataFrame(
np.logical_or(df, other, *args, **kwargs)
),
infer_dtypes="bool",
)
_logical_xor = Binary.register(
lambda df, other, *args, **kwargs: pandas.DataFrame(
np.logical_xor(df, other, *args, **kwargs)
),
infer_dtypes="bool",
)
def where(self, cond, other, **kwargs):
assert isinstance(
cond, type(self)
), "Must have the same QueryCompiler subclass to perform this operation"
# it's doesn't work if `other` is Series._query_compiler because
# `n_ary_op` performs columns copartition both for `cond` and `other`.
if isinstance(other, type(self)) and other._shape_hint is not None:
other = other.to_pandas()
if isinstance(other, type(self)):
# Make sure to set join_type=None so the `where` result always has
# the same row and column labels as `self`.
new_modin_frame = self._modin_frame.n_ary_op(
lambda df, cond, other: df.where(cond, other, **kwargs),
[
cond._modin_frame,
other._modin_frame,
],
join_type=None,
)
# This will be a Series of scalars to be applied based on the condition
# dataframe.
else:
def where_builder_series(df, cond):
return df.where(cond, other, **kwargs)
new_modin_frame = self._modin_frame.n_ary_op(
where_builder_series, [cond._modin_frame], join_type="left"
)
return self.__constructor__(new_modin_frame)
def merge(self, right, **kwargs):
if RangePartitioning.get():
try:
return MergeImpl.range_partitioning_merge(self, right, kwargs)
except NotImplementedError as e:
message = (
f"Can't use range-partitioning merge implementation because of: {e}"
+ "\nFalling back to a row-axis implementation."
)
get_logger().info(message)
return MergeImpl.row_axis_merge(self, right, kwargs)
def join(self, right, **kwargs):
on = kwargs.get("on", None)
how = kwargs.get("how", "left")
sort = kwargs.get("sort", False)
right_to_broadcast = right._modin_frame.combine()
if how in ["left", "inner"]:
def map_func(left, right, kwargs=kwargs): # pragma: no cover
return pandas.DataFrame.join(left, right, **kwargs)
new_self = self.__constructor__(
self._modin_frame.broadcast_apply_full_axis(
axis=1,
func=map_func,
# We're going to explicitly change the shape across the 1-axis,
# so we want for partitioning to adapt as well
keep_partitioning=False,
num_splits=merge_partitioning(
self._modin_frame, right._modin_frame, axis=1
),
other=right_to_broadcast,
)
)
return new_self.sort_rows_by_column_values(on) if sort else new_self
else:
return self.default_to_pandas(pandas.DataFrame.join, right, **kwargs)
# END Inter-Data operations
# Reindex/reset_index (may shuffle data)
def reindex(self, axis, labels, **kwargs):
new_index, indexer = (self.index, None) if axis else self.index.reindex(labels)
new_columns, _ = self.columns.reindex(labels) if axis else (self.columns, None)
new_dtypes = None
if (
self._modin_frame.has_materialized_dtypes
and kwargs.get("method", None) is None
):
# For columns, defining types is easier because we don't have to calculate the common
# type, since the entire column is filled. A simple `reindex` covers our needs.
# For rows, we can avoid calculating common types if we know that no new strings of
# arbitrary type have been added (this information is in `indexer`).
dtype = pandas.Index([kwargs.get("fill_value", np.nan)]).dtype
if axis == 0:
new_dtypes = self.dtypes.copy()
# "-1" means that the required labels are missing in the dataframe and the
# corresponding rows will be filled with "fill_value" that may change the column type.
if indexer is not None and -1 in indexer:
for col, col_dtype in new_dtypes.items():
new_dtypes[col] = find_common_type((col_dtype, dtype))
else:
new_dtypes = self.dtypes.reindex(labels, fill_value=dtype)
new_modin_frame = self._modin_frame.apply_full_axis(
axis,
lambda df: df.reindex(labels=labels, axis=axis, **kwargs),
new_index=new_index,
new_columns=new_columns,
dtypes=new_dtypes,
)
return self.__constructor__(new_modin_frame)
def reset_index(self, **kwargs):
if self.lazy_execution:
def _reset(df, *axis_lengths, partition_idx): # pragma: no cover
df = df.reset_index(**kwargs)
if isinstance(df.index, pandas.RangeIndex):
# If the resulting index is a pure RangeIndex that means that
# `.reset_index` actually dropped all of the levels of the
# original index and so we have to recompute it manually for each partition
start = sum(axis_lengths[:partition_idx])
stop = sum(axis_lengths[: partition_idx + 1])
df.index = pandas.RangeIndex(start, stop)
return df
new_columns = None
if kwargs["drop"]:
dtypes = self._modin_frame.copy_dtypes_cache()
if self._modin_frame.has_columns_cache:
new_columns = self._modin_frame.copy_columns_cache(
copy_lengths=True
)
else:
# concat index dtypes with column dtypes
index_dtypes = self._modin_frame._index_cache.maybe_get_dtypes()
try:
dtypes = ModinDtypes.concat(
[
index_dtypes,
self._modin_frame._dtypes,
]
)
except NotImplementedError:
# may raise on duplicated names in materialized 'self.dtypes'
dtypes = None
if (
# can precompute new columns if we know columns and index names
self._modin_frame.has_materialized_columns
and index_dtypes is not None
):
empty_index = (
pandas.Index([0], name=index_dtypes.index[0])
if len(index_dtypes) == 1
else pandas.MultiIndex.from_arrays(
[[i] for i in range(len(index_dtypes))],
names=index_dtypes.index,
)
)
new_columns = (
pandas.DataFrame(columns=self.columns, index=empty_index)
.reset_index(**kwargs)
.columns
)
return self.__constructor__(
self._modin_frame.apply_full_axis(
axis=1,
func=_reset,
enumerate_partitions=True,
new_columns=new_columns,
dtypes=dtypes,
sync_labels=False,
pass_axis_lengths_to_partitions=True,
)
)
allow_duplicates = kwargs.pop("allow_duplicates", lib.no_default)
names = kwargs.pop("names", None)
if allow_duplicates not in (lib.no_default, False) or names is not None:
return self.default_to_pandas(
pandas.DataFrame.reset_index,
allow_duplicates=allow_duplicates,
names=names,
**kwargs,
)
drop = kwargs.get("drop", False)
level = kwargs.get("level", None)
new_index = None
if level is not None:
if not isinstance(level, (tuple, list)):
level = [level]
level = [self.index._get_level_number(lev) for lev in level]
uniq_sorted_level = sorted(set(level))
if len(uniq_sorted_level) < self.index.nlevels:
# We handle this by separately computing the index. We could just
# put the labels into the data and pull them back out, but that is
# expensive.
new_index = (
self.index.droplevel(uniq_sorted_level)
if len(level) < self.index.nlevels
else pandas.RangeIndex(len(self.index))
)
elif not drop:
uniq_sorted_level = list(range(self.index.nlevels))
if not drop:
if len(uniq_sorted_level) < self.index.nlevels:
# These are the index levels that will remain after the reset_index
keep_levels = [
i for i in range(self.index.nlevels) if i not in uniq_sorted_level
]
new_copy = self.copy()
# Change the index to have only the levels that will be inserted
# into the data. We will replace the old levels later.
new_copy.index = self.index.droplevel(keep_levels)
new_copy.index.names = [
(
"level_{}".format(level_value)
if new_copy.index.names[level_index] is None
else new_copy.index.names[level_index]
)
for level_index, level_value in enumerate(uniq_sorted_level)
]
new_modin_frame = new_copy._modin_frame.from_labels()
# Replace the levels that will remain as a part of the index.
new_modin_frame.index = new_index
else:
new_modin_frame = self._modin_frame.from_labels()
if isinstance(new_modin_frame.columns, pandas.MultiIndex):
# Fix col_level and col_fill in generated column names because from_labels works with assumption
# that col_level and col_fill are not specified but it expands tuples in level names.
col_level = kwargs.get("col_level", 0)
col_fill = kwargs.get("col_fill", "")
if col_level != 0 or col_fill != "":
# Modify generated column names if col_level and col_fil have values different from default.
levels_names_list = [
f"level_{level_index}" if level_name is None else level_name
for level_index, level_name in enumerate(self.index.names)
]
if col_fill is None:
# Initialize col_fill if it is None.
# This is some weird undocumented Pandas behavior to take first
# element of the last column name.
last_col_name = levels_names_list[uniq_sorted_level[-1]]
last_col_name = (
list(last_col_name)
if isinstance(last_col_name, tuple)
else [last_col_name]
)
if len(last_col_name) not in (1, self.columns.nlevels):
raise ValueError(
"col_fill=None is incompatible "
+ f"with incomplete column name {last_col_name}"
)
col_fill = last_col_name[0]
columns_list = new_modin_frame.columns.tolist()
for level_index, level_value in enumerate(uniq_sorted_level):
level_name = levels_names_list[level_value]
# Expand tuples into separate items and fill the rest with col_fill
top_level = [col_fill] * col_level
middle_level = (
list(level_name)
if isinstance(level_name, tuple)
else [level_name]
)
bottom_level = [col_fill] * (
self.columns.nlevels - (col_level + len(middle_level))
)
item = tuple(top_level + middle_level + bottom_level)
if len(item) > self.columns.nlevels:
raise ValueError(
"Item must have length equal to number of levels."
)
columns_list[level_index] = item
new_modin_frame.columns = pandas.MultiIndex.from_tuples(
columns_list, names=self.columns.names
)
new_self = self.__constructor__(new_modin_frame)
else:
new_self = self.copy()
new_self.index = (
# Cheaper to compute row lengths than index
pandas.RangeIndex(sum(new_self._modin_frame.row_lengths))
if new_index is None
else new_index
)
return new_self
def set_index_from_columns(
self, keys: List[Hashable], drop: bool = True, append: bool = False
):
new_modin_frame = self._modin_frame.to_labels(keys)
if append:
arrays = []
# Appending keeps the original order of the index levels, then appends the
# new index objects.
names = list(self.index.names)
if isinstance(self.index, pandas.MultiIndex):
for i in range(self.index.nlevels):
arrays.append(self.index._get_level_values(i))
else:
arrays.append(self.index)
# Add the names in the correct order.
names.extend(new_modin_frame.index.names)
if isinstance(new_modin_frame.index, pandas.MultiIndex):
for i in range(new_modin_frame.index.nlevels):
arrays.append(new_modin_frame.index._get_level_values(i))
else:
arrays.append(new_modin_frame.index)
new_modin_frame.index = ensure_index_from_sequences(arrays, names)
if not drop:
# The algebraic operator for this operation always drops the column, but we
# can copy the data in this object and just use the index from the result of
# the query compiler call.
result = self._modin_frame.copy()
result.index = new_modin_frame.index
else:
result = new_modin_frame
return self.__constructor__(result)
# END Reindex/reset_index
# Transpose
# For transpose, we aren't going to immediately copy everything. Since the
# actual transpose operation is very fast, we will just do it before any
# operation that gets called on the transposed data. See _prepare_method
# for how the transpose is applied.
#
# Our invariants assume that the blocks are transposed, but not the
# data inside. Sometimes we have to reverse this transposition of blocks
# for simplicity of implementation.
def transpose(self, *args, **kwargs):
# Switch the index and columns and transpose the data within the blocks.
return self.__constructor__(self._modin_frame.transpose())
def is_series_like(self):
return len(self.columns) == 1 or len(self.index) == 1
# END Transpose
# TreeReduce operations
count = TreeReduce.register(pandas.DataFrame.count, pandas.DataFrame.sum)
def _dtypes_sum(dtypes: pandas.Series, *func_args, **func_kwargs): # noqa: GL08
# The common type evaluation for `TreeReduce` operator may differ depending
# on the pandas function, so it's better to pass a evaluation function that
# should be defined for each Modin's function.
return find_common_type(dtypes.tolist())
sum = TreeReduce.register(pandas.DataFrame.sum, compute_dtypes=_dtypes_sum)
prod = TreeReduce.register(pandas.DataFrame.prod)
any = TreeReduce.register(pandas.DataFrame.any, pandas.DataFrame.any)
all = TreeReduce.register(pandas.DataFrame.all, pandas.DataFrame.all)
# memory_usage adds an extra column for index usage, but we don't want to distribute
# the index memory usage calculation.
_memory_usage_without_index = TreeReduce.register(
pandas.DataFrame.memory_usage,
lambda x, *args, **kwargs: pandas.DataFrame.sum(x),
axis=0,
)
def memory_usage(self, **kwargs):
index = kwargs.get("index", True)
deep = kwargs.get("deep", False)
usage_without_index = self._memory_usage_without_index(index=False, deep=deep)
return (
self.from_pandas(
pandas.DataFrame(
[self.index.memory_usage()],
columns=["Index"],
index=[MODIN_UNNAMED_SERIES_LABEL],
),
data_cls=type(self._modin_frame),
).concat(axis=1, other=[usage_without_index])
if index
else usage_without_index
)
def max(self, axis, **kwargs):
def map_func(df, **kwargs):
return pandas.DataFrame.max(df, **kwargs)
def reduce_func(df, **kwargs):
if kwargs.get("numeric_only", False):
kwargs = kwargs.copy()
kwargs["numeric_only"] = False
return pandas.DataFrame.max(df, **kwargs)
return TreeReduce.register(map_func, reduce_func)(self, axis=axis, **kwargs)
def min(self, axis, **kwargs):
def map_func(df, **kwargs):
return pandas.DataFrame.min(df, **kwargs)
def reduce_func(df, **kwargs):
if kwargs.get("numeric_only", False):
kwargs = kwargs.copy()
kwargs["numeric_only"] = False
return pandas.DataFrame.min(df, **kwargs)
return TreeReduce.register(map_func, reduce_func)(self, axis=axis, **kwargs)
def mean(self, axis, **kwargs):
if kwargs.get("level") is not None or axis is None:
return self.default_to_pandas(pandas.DataFrame.mean, axis=axis, **kwargs)
skipna = kwargs.get("skipna", True)
# TODO-FIX: this function may work incorrectly with user-defined "numeric" values.
# Since `count(numeric_only=True)` discards all unknown "numeric" types, we can get incorrect
# divisor inside the reduce function.
def map_fn(df, numeric_only=False, **kwargs):
"""
Perform Map phase of the `mean`.
Compute sum and number of elements in a given partition.
"""
result = pandas.DataFrame(
{
"sum": df.sum(axis=axis, skipna=skipna, numeric_only=numeric_only),
"count": df.count(axis=axis, numeric_only=numeric_only),
}
)
return result if axis else result.T
def reduce_fn(df, **kwargs):
"""
Perform Reduce phase of the `mean`.
Compute sum for all the the partitions and divide it to
the total number of elements.
"""
sum_cols = df["sum"] if axis else df.loc["sum"]
count_cols = df["count"] if axis else df.loc["count"]
if not isinstance(sum_cols, pandas.Series):
# If we got `NaN` as the result of the sum in any axis partition,
# then we must consider the whole sum as `NaN`, so setting `skipna=False`
sum_cols = sum_cols.sum(axis=axis, skipna=False)
count_cols = count_cols.sum(axis=axis, skipna=False)
return sum_cols / count_cols
def compute_dtypes_fn(dtypes, axis, **kwargs):
"""
Compute the resulting Series dtype.
When computing along rows and there are numeric and boolean columns
Pandas returns `object`. In all other cases - `float64`.
"""
if (
axis == 1
and any(is_bool_dtype(t) for t in dtypes)
and any(is_numeric_dtype(t) for t in dtypes)
):
return "object"
return "float64"
return TreeReduce.register(
map_fn,
reduce_fn,
compute_dtypes=compute_dtypes_fn,
)(self, axis=axis, **kwargs)
# END TreeReduce operations
# Reduce operations
idxmax = Reduce.register(pandas.DataFrame.idxmax)
idxmin = Reduce.register(pandas.DataFrame.idxmin)
def median(self, axis, **kwargs):
if axis is None:
return self.default_to_pandas(pandas.DataFrame.median, axis=axis, **kwargs)
return Reduce.register(pandas.DataFrame.median)(self, axis=axis, **kwargs)
def nunique(self, axis=0, dropna=True):
if not RangePartitioning.get():
return Reduce.register(pandas.DataFrame.nunique)(
self, axis=axis, dropna=dropna
)
unsupported_message = ""
if axis != 0:
unsupported_message += (
"Range-partitioning 'nunique()' is only supported for 'axis=0'.\n"
)
if len(self.columns) > 1:
unsupported_message += "Range-partitioning 'nunique()' is only supported for a signle-column dataframe.\n"
if len(unsupported_message) > 0:
message = (
f"Can't use range-partitioning implementation for 'nunique' because:\n{unsupported_message}"
+ "Falling back to a full-axis reduce implementation."
)
get_logger().info(message)
ErrorMessage.warn(message)
return Reduce.register(pandas.DataFrame.nunique)(
self, axis=axis, dropna=dropna
)
# compute '.nunique()' for each row partitions
new_modin_frame = self._modin_frame._apply_func_to_range_partitioning(
key_columns=self.columns.tolist(),
func=lambda df: df.nunique(dropna=dropna).to_frame(),
)
# sum the results of each row part to get the final value
new_modin_frame = new_modin_frame.reduce(axis=0, function=lambda df: df.sum())
return self.__constructor__(new_modin_frame, shape_hint="column")
def skew(self, axis, **kwargs):
if axis is None:
return self.default_to_pandas(pandas.DataFrame.skew, axis=axis, **kwargs)
return Reduce.register(pandas.DataFrame.skew)(self, axis=axis, **kwargs)
def kurt(self, axis, **kwargs):
if axis is None:
return self.default_to_pandas(pandas.DataFrame.kurt, axis=axis, **kwargs)
return Reduce.register(pandas.DataFrame.kurt)(self, axis=axis, **kwargs)