/
query_compiler.py
1888 lines (1561 loc) · 62.2 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.
import abc
from modin.data_management.functions.default_methods import (
DataFrameDefault,
SeriesDefault,
DateTimeDefault,
StrDefault,
BinaryDefault,
ResampleDefault,
RollingDefault,
CatDefault,
GroupByDefault,
)
from modin.error_message import ErrorMessage
from pandas.core.dtypes.common import is_scalar
import pandas.core.resample
import pandas
import numpy as np
def _get_axis(axis):
def axis_getter(self):
ErrorMessage.default_to_pandas(f"DataFrame.get_axis({axis})")
return self.to_pandas().axes[axis]
return axis_getter
def _set_axis(axis):
def axis_setter(self, labels):
new_qc = DataFrameDefault.register(pandas.DataFrame.set_axis)(
self, axis=axis, labels=labels
)
self.__dict__.update(new_qc.__dict__)
return axis_setter
class BaseQueryCompiler(abc.ABC):
"""Abstract Class that handles the queries to Modin dataframes.
Note: See the Abstract Methods and Fields section immediately below this
for a list of requirements for subclassing this object.
"""
@abc.abstractmethod
def default_to_pandas(self, pandas_op, *args, **kwargs):
"""
Default to pandas behavior.
Parameters
----------
pandas_op : callable
The operation to apply, must be compatible pandas DataFrame call
args
The arguments for the `pandas_op`
kwargs
The keyword arguments for the `pandas_op`
Returns
-------
BaseQueryCompiler
The result of the `pandas_op`, converted back to BaseQueryCompiler
"""
pass
# Abstract Methods and Fields: Must implement in children classes
# In some cases, there you may be able to use the same implementation for
# some of these abstract methods, but for the sake of generality they are
# treated differently.
lazy_execution = False
# Metadata modification abstract methods
def add_prefix(self, prefix, axis=1):
if axis:
return DataFrameDefault.register(pandas.DataFrame.add_prefix)(
self, prefix=prefix
)
else:
return SeriesDefault.register(pandas.Series.add_prefix)(self, prefix=prefix)
def add_suffix(self, suffix, axis=1):
if axis:
return DataFrameDefault.register(pandas.DataFrame.add_suffix)(
self, suffix=suffix
)
else:
return SeriesDefault.register(pandas.Series.add_suffix)(self, suffix=suffix)
# END Metadata modification abstract methods
# Abstract 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 DataFrameDefault.register(pandas.DataFrame.copy)(self)
# END Abstract copy
# Abstract join and append helper functions
def concat(self, axis, other, **kwargs):
"""Concatenates two objects together.
Args:
axis: The axis index object to join (0 for columns, 1 for index).
other: The other_index to concat with.
Returns:
Concatenated objects.
"""
concat_join = ["inner", "outer"]
def concat(df, axis, other, **kwargs):
kwargs.pop("join_axes", None)
ignore_index = kwargs.get("ignore_index", False)
if kwargs.get("join", "outer") in concat_join:
if not isinstance(other, list):
other = [other]
other = [df] + other
result = pandas.concat(other, axis=axis, **kwargs)
else:
if isinstance(other, (list, np.ndarray)) and len(other) == 1:
other = other[0]
ignore_index = kwargs.pop("ignore_index", None)
kwargs["how"] = kwargs.pop("join", None)
result = df.join(other, rsuffix="r_", **kwargs)
if ignore_index:
if axis == 0:
result = result.reset_index(drop=True)
else:
result.columns = pandas.RangeIndex(len(result.columns))
return result
return DataFrameDefault.register(concat)(self, axis=axis, other=other, **kwargs)
# END Abstract join and append helper functions
# Data Management Methods
@abc.abstractmethod
def free(self):
"""In the future, this will hopefully trigger a cleanup of this object."""
# TODO create a way to clean up this object.
pass
# END Data Management Methods
# To/From Pandas
@abc.abstractmethod
def to_pandas(self):
"""Converts Modin DataFrame to Pandas DataFrame.
Returns:
Pandas DataFrame of the QueryCompiler.
"""
pass
@classmethod
@abc.abstractmethod
def from_pandas(cls, df, data_cls):
"""Improve simple Pandas DataFrame to an advanced and superior Modin DataFrame.
Parameters
----------
df: pandas.DataFrame
The pandas DataFrame to convert from.
data_cls :
Modin DataFrame object to convert to.
Returns
-------
BaseQueryCompiler
QueryCompiler containing data from the Pandas DataFrame.
"""
pass
# END To/From Pandas
# From Arrow
@classmethod
@abc.abstractmethod
def from_arrow(cls, at, data_cls):
"""Improve simple Arrow Table to an advanced and superior Modin DataFrame.
Parameters
----------
at : Arrow Table
The Arrow Table to convert from.
data_cls :
Modin DataFrame object to convert to.
Returns
-------
BaseQueryCompiler
QueryCompiler containing data from the Pandas DataFrame.
"""
pass
# END From Arrow
# To NumPy
def to_numpy(self, **kwargs):
"""
Converts Modin DataFrame to NumPy array.
Returns
-------
NumPy array of the QueryCompiler.
"""
return DataFrameDefault.register(pandas.DataFrame.to_numpy)(self, **kwargs)
# END To NumPy
# Abstract inter-data 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.
def add(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.add)(self, other=other, **kwargs)
def combine(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.combine)(
self, other=other, **kwargs
)
def combine_first(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.combine_first)(
self, other=other, **kwargs
)
def eq(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.eq)(self, other=other, **kwargs)
def floordiv(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.floordiv)(
self, other=other, **kwargs
)
def ge(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.ge)(self, other=other, **kwargs)
def gt(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.gt)(self, other=other, **kwargs)
def le(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.le)(self, other=other, **kwargs)
def lt(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.lt)(self, other=other, **kwargs)
def mod(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.mod)(self, other=other, **kwargs)
def mul(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.mul)(self, other=other, **kwargs)
def corr(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.corr)(self, **kwargs)
def cov(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.cov)(self, **kwargs)
def dot(self, other, **kwargs):
if kwargs.get("squeeze_self", False):
applyier = pandas.Series.dot
else:
applyier = pandas.DataFrame.dot
return BinaryDefault.register(applyier)(self, other=other, **kwargs)
def ne(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.ne)(self, other=other, **kwargs)
def pow(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.pow)(self, other=other, **kwargs)
def rfloordiv(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.rfloordiv)(
self, other=other, **kwargs
)
def rmod(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.rmod)(
self, other=other, **kwargs
)
def rpow(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.rpow)(
self, other=other, **kwargs
)
def rsub(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.rsub)(
self, other=other, **kwargs
)
def rtruediv(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.rtruediv)(
self, other=other, **kwargs
)
def sub(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.sub)(self, other=other, **kwargs)
def truediv(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.truediv)(
self, other=other, **kwargs
)
def __and__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__and__)(
self, other=other, **kwargs
)
def __or__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__or__)(
self, other=other, **kwargs
)
def __rand__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__rand__)(
self, other=other, **kwargs
)
def __ror__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__ror__)(
self, other=other, **kwargs
)
def __rxor__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__rxor__)(
self, other=other, **kwargs
)
def __xor__(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.__xor__)(
self, other=other, **kwargs
)
def df_update(self, other, **kwargs):
return BinaryDefault.register(pandas.DataFrame.update, inplace=True)(
self, other=other, **kwargs
)
def series_update(self, other, **kwargs):
return BinaryDefault.register(pandas.Series.update, inplace=True)(
self, other=other, squeeze_self=True, squeeze_other=True, **kwargs
)
def clip(self, lower, upper, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.clip)(
self, lower=lower, upper=upper, **kwargs
)
def where(self, cond, other, **kwargs):
"""Gets values from this manager where cond is true else from other.
Args:
cond: Condition on which to evaluate values.
Returns:
New QueryCompiler with updated data and index.
"""
return DataFrameDefault.register(pandas.DataFrame.where)(
self, cond=cond, other=other, **kwargs
)
def merge(self, right, **kwargs):
"""
Merge DataFrame or named Series objects with a database-style join.
Parameters
----------
right : BaseQueryCompiler
The query compiler of the right DataFrame to merge with.
Returns
-------
BaseQueryCompiler
A new query compiler that contains result of the merge.
Notes
-----
See pd.merge or pd.DataFrame.merge for more info on kwargs.
"""
return DataFrameDefault.register(pandas.DataFrame.merge)(
self, right=right, **kwargs
)
def join(self, right, **kwargs):
"""
Join columns of another DataFrame.
Parameters
----------
right : BaseQueryCompiler
The query compiler of the right DataFrame to join with.
Returns
-------
BaseQueryCompiler
A new query compiler that contains result of the join.
Notes
-----
See pd.DataFrame.join for more info on kwargs.
"""
return DataFrameDefault.register(pandas.DataFrame.join)(self, right, **kwargs)
# END Abstract inter-data operations
# Abstract Transpose
def transpose(self, *args, **kwargs):
"""Transposes this QueryCompiler.
Returns:
Transposed new QueryCompiler.
"""
return DataFrameDefault.register(pandas.DataFrame.transpose)(
self, *args, **kwargs
)
def columnarize(self):
"""
Transposes this QueryCompiler if it has a single row but multiple columns.
This method should be called for QueryCompilers representing a Series object,
i.e. self.is_series_like() should be True.
Returns
-------
BaseQueryCompiler
Transposed new QueryCompiler or self.
"""
if len(self.columns) != 1 or (
len(self.index) == 1 and self.index[0] == "__reduced__"
):
return self.transpose()
return self
def is_series_like(self):
"""Return True if QueryCompiler has a single column or row"""
return len(self.columns) == 1 or len(self.index) == 1
# END Abstract Transpose
# Abstract reindex/reset_index (may shuffle data)
def reindex(self, axis, labels, **kwargs):
"""Fits a new index for this Manger.
Args:
axis: The axis index object to target the reindex on.
labels: New labels to conform 'axis' on to.
Returns:
New QueryCompiler with updated data and new index.
"""
return DataFrameDefault.register(pandas.DataFrame.reindex)(
self, axis=axis, labels=labels, **kwargs
)
def reset_index(self, **kwargs):
"""Removes all levels from index and sets a default level_0 index.
Returns:
New QueryCompiler with updated data and reset index.
"""
return DataFrameDefault.register(pandas.DataFrame.reset_index)(self, **kwargs)
# END Abstract reindex/reset_index
# Full Reduce operations
#
# These operations result in a reduced dimensionality of data.
# Currently, this means a Pandas Series will be returned, but in the future
# we will implement a Distributed Series, and this will be returned
# instead.
def is_monotonic(self):
"""Return boolean if values in the object are monotonic_increasing.
Returns
-------
bool
"""
return SeriesDefault.register(pandas.Series.is_monotonic)(self)
def is_monotonic_decreasing(self):
"""Return boolean if values in the object are monotonic_decreasing.
Returns
-------
bool
"""
return SeriesDefault.register(pandas.Series.is_monotonic_decreasing)(self)
def count(self, **kwargs):
"""Counts the number of non-NaN objects for each column or row.
Return:
Pandas series containing counts of non-NaN objects from each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.count)(self, **kwargs)
def max(self, **kwargs):
"""Returns the maximum value for each column or row.
Return:
Pandas series with the maximum values from each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.max)(self, **kwargs)
def mean(self, **kwargs):
"""Returns the mean for each numerical column or row.
Return:
Pandas series containing the mean from each numerical column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.mean)(self, **kwargs)
def min(self, **kwargs):
"""Returns the minimum from each column or row.
Return:
Pandas series with the minimum value from each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.min)(self, **kwargs)
def prod(self, **kwargs):
"""Returns the product of each numerical column or row.
Return:
Pandas series with the product of each numerical column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.prod)(self, **kwargs)
def sum(self, **kwargs):
"""Returns the sum of each numerical column or row.
Return:
Pandas series with the sum of each numerical column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.sum)(self, **kwargs)
def to_datetime(self, *args, **kwargs):
return SeriesDefault.register(pandas.to_datetime)(self, *args, **kwargs)
# END Abstract full Reduce operations
# Abstract map partitions operations
# These operations are operations that apply a function to every partition.
def abs(self):
return DataFrameDefault.register(pandas.DataFrame.abs)(self)
def applymap(self, func):
return DataFrameDefault.register(pandas.DataFrame.applymap)(self, func=func)
def conj(self, **kwargs):
"""
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained
by changing the sign of its imaginary part.
"""
def conj(df, *args, **kwargs):
return pandas.DataFrame(np.conj(df))
return DataFrameDefault.register(conj)(self, **kwargs)
def isin(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.isin)(self, **kwargs)
def isna(self):
return DataFrameDefault.register(pandas.DataFrame.isna)(self)
def negative(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.__neg__)(self, **kwargs)
def notna(self):
return DataFrameDefault.register(pandas.DataFrame.notna)(self)
def round(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.round)(self, **kwargs)
def replace(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.replace)(self, **kwargs)
def series_view(self, **kwargs):
return SeriesDefault.register(pandas.Series.view)(self, **kwargs)
def to_numeric(self, *args, **kwargs):
return SeriesDefault.register(pandas.to_numeric)(self, *args, **kwargs)
def unique(self, **kwargs):
return SeriesDefault.register(pandas.Series.unique)(self, **kwargs)
def searchsorted(self, **kwargs):
return SeriesDefault.register(pandas.Series.searchsorted)(self, **kwargs)
# END Abstract map partitions operations
def value_counts(self, **kwargs):
return SeriesDefault.register(pandas.Series.value_counts)(self, **kwargs)
def stack(self, level, dropna):
return DataFrameDefault.register(pandas.DataFrame.stack)(
self, level=level, dropna=dropna
)
# Abstract map partitions across select indices
def astype(self, col_dtypes, **kwargs):
"""Converts columns dtypes to given dtypes.
Args:
col_dtypes: Dictionary of {col: dtype,...} where col is the column
name and dtype is a numpy dtype.
Returns:
DataFrame with updated dtypes.
"""
return DataFrameDefault.register(pandas.DataFrame.astype)(
self, dtype=col_dtypes, **kwargs
)
@property
def dtypes(self):
return self.to_pandas().dtypes
# END Abstract map partitions across select indices
# Abstract column/row partitions reduce operations
#
# These operations result in a reduced dimensionality of data.
# Currently, this means a Pandas Series will be returned, but in the future
# we will implement a Distributed Series, and this will be returned
# instead.
def all(self, **kwargs):
"""Returns whether all the elements are true, potentially over an axis.
Return:
Pandas Series containing boolean values or boolean.
"""
return DataFrameDefault.register(pandas.DataFrame.all)(self, **kwargs)
def any(self, **kwargs):
"""Returns whether any the elements are true, potentially over an axis.
Return:
Pandas Series containing boolean values or boolean.
"""
return DataFrameDefault.register(pandas.DataFrame.any)(self, **kwargs)
def first_valid_index(self):
"""Returns index of first non-NaN/NULL value.
Return:
Scalar of index name.
"""
return (
DataFrameDefault.register(pandas.DataFrame.first_valid_index)(self)
.to_pandas()
.squeeze()
)
def idxmax(self, **kwargs):
"""Returns the first occurance of the maximum over requested axis.
Returns:
Series containing the maximum of each column or axis.
"""
return DataFrameDefault.register(pandas.DataFrame.idxmax)(self, **kwargs)
def idxmin(self, **kwargs):
"""Returns the first occurance of the minimum over requested axis.
Returns:
Series containing the minimum of each column or axis.
"""
return DataFrameDefault.register(pandas.DataFrame.idxmin)(self, **kwargs)
def last_valid_index(self):
"""Returns index of last non-NaN/NULL value.
Return:
Scalar of index name.
"""
return (
DataFrameDefault.register(pandas.DataFrame.last_valid_index)(self)
.to_pandas()
.squeeze()
)
def median(self, **kwargs):
"""Returns median of each column or row.
Returns:
Series containing the median of each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.median)(self, **kwargs)
def memory_usage(self, **kwargs):
"""Returns the memory usage of each column.
Returns:
Series containing the memory usage of each column.
"""
return DataFrameDefault.register(pandas.DataFrame.memory_usage)(self, **kwargs)
def nunique(self, **kwargs):
"""Returns the number of unique items over each column or row.
Returns:
Series of ints indexed by column or index names.
"""
return DataFrameDefault.register(pandas.DataFrame.nunique)(self, **kwargs)
def quantile_for_single_value(self, **kwargs):
"""Returns quantile of each column or row.
Returns:
Series containing the quantile of each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.quantile)(self, **kwargs)
def skew(self, **kwargs):
"""Returns skew of each column or row.
Returns:
Series containing the skew of each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.skew)(self, **kwargs)
def sem(self, **kwargs):
"""
Returns standard deviation of the mean over requested axis.
Returns
-------
BaseQueryCompiler
QueryCompiler containing the standard deviation of the mean over requested axis.
"""
return DataFrameDefault.register(pandas.DataFrame.sem)(self, **kwargs)
def std(self, **kwargs):
"""Returns standard deviation of each column or row.
Returns:
Series containing the standard deviation of each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.std)(self, **kwargs)
def var(self, **kwargs):
"""Returns variance of each column or row.
Returns:
Series containing the variance of each column or row.
"""
return DataFrameDefault.register(pandas.DataFrame.var)(self, **kwargs)
# END Abstract column/row partitions reduce operations
# Abstract column/row partitions reduce operations over select indices
#
# These operations result in a reduced dimensionality of data.
# Currently, this means a Pandas Series will be returned, but in the future
# we will implement a Distributed Series, and this will be returned
# instead.
def describe(self, **kwargs):
"""Generates descriptive statistics.
Returns:
DataFrame object containing the descriptive statistics of the DataFrame.
"""
return DataFrameDefault.register(pandas.DataFrame.describe)(self, **kwargs)
# END Abstract column/row partitions reduce operations over select indices
# Map across rows/columns
# These operations require some global knowledge of the full column/row
# that is being operated on. This means that we have to put all of that
# data in the same place.
def cumsum(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.cumsum)(self, **kwargs)
def cummax(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.cummax)(self, **kwargs)
def cummin(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.cummin)(self, **kwargs)
def cumprod(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.cumprod)(self, **kwargs)
def diff(self, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.diff)(self, **kwargs)
def dropna(self, **kwargs):
"""Returns a new QueryCompiler with null values dropped along given axis.
Return:
New QueryCompiler
"""
return DataFrameDefault.register(pandas.DataFrame.dropna)(self, **kwargs)
def nlargest(self, n=5, columns=None, keep="first"):
if columns is None:
return SeriesDefault.register(pandas.Series.nlargest)(self, n=n, keep=keep)
else:
return DataFrameDefault.register(pandas.DataFrame.nlargest)(
self, n=n, columns=columns, keep=keep
)
def nsmallest(self, n=5, columns=None, keep="first"):
if columns is None:
return SeriesDefault.register(pandas.Series.nsmallest)(self, n=n, keep=keep)
else:
return DataFrameDefault.register(pandas.DataFrame.nsmallest)(
self, n=n, columns=columns, keep=keep
)
def eval(self, expr, **kwargs):
"""Returns a new QueryCompiler with expr evaluated on columns.
Args:
expr: The string expression to evaluate.
Returns:
A new QueryCompiler with new columns after applying expr.
"""
return DataFrameDefault.register(pandas.DataFrame.eval)(
self, expr=expr, **kwargs
)
def mode(self, **kwargs):
"""Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated.
"""
return DataFrameDefault.register(pandas.DataFrame.mode)(self, **kwargs)
def fillna(self, **kwargs):
"""Replaces NaN values with the method provided.
Returns:
A new QueryCompiler with null values filled.
"""
return DataFrameDefault.register(pandas.DataFrame.fillna)(self, **kwargs)
def query(self, expr, **kwargs):
"""Query columns of the QueryCompiler with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
QueryCompiler containing the rows where the boolean expression is satisfied.
"""
return DataFrameDefault.register(pandas.DataFrame.query)(
self, expr=expr, **kwargs
)
def rank(self, **kwargs):
"""Computes numerical rank along axis. Equal values are set to the average.
Returns:
QueryCompiler containing the ranks of the values along an axis.
"""
return DataFrameDefault.register(pandas.DataFrame.rank)(self, **kwargs)
def sort_index(self, **kwargs):
"""Sorts the data with respect to either the columns or the indices.
Returns:
QueryCompiler containing the data sorted by columns or indices.
"""
return DataFrameDefault.register(pandas.DataFrame.sort_index)(self, **kwargs)
def melt(self, *args, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.melt)(self, *args, **kwargs)
def sort_columns_by_row_values(self, rows, ascending=True, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.sort_values)(
self, by=rows, axis=1, ascending=ascending, **kwargs
)
def sort_rows_by_column_values(self, rows, ascending=True, **kwargs):
return DataFrameDefault.register(pandas.DataFrame.sort_values)(
self, by=rows, axis=0, ascending=ascending, **kwargs
)
# END Abstract map across rows/columns
# Map across rows/columns
# These operations require some global knowledge of the full column/row
# that is being operated on. This means that we have to put all of that
# data in the same place.
def quantile_for_list_of_values(self, **kwargs):
"""Returns Manager containing quantiles along an axis for numeric columns.
Returns:
QueryCompiler containing quantiles of original QueryCompiler along an axis.
"""
return DataFrameDefault.register(pandas.DataFrame.quantile)(self, **kwargs)
# END Abstract map across rows/columns
# Abstract __getitem__ methods
def getitem_array(self, key):
"""
Get column or row data specified by key.
Parameters
----------
key : BaseQueryCompiler, numpy.ndarray, pandas.Index or list
Target numeric indices or labels by which to retrieve data.
Returns
-------
BaseQueryCompiler
A new Query Compiler.
"""
def getitem_array(df, key):
return df[key]
return DataFrameDefault.register(getitem_array)(self, key)
def getitem_column_array(self, key, numeric=False):
"""Get column data for target labels.
Args:
key: Target labels by which to retrieve data.
numeric: A boolean representing whether or not the key passed in represents
the numeric index or the named index.
Returns:
A new Query Compiler.
"""
def get_column(df, key):
if numeric:
return df.iloc[:, key]
else:
return df[key]
return DataFrameDefault.register(get_column)(self, key=key)
def getitem_row_array(self, key):
"""Get row data for target labels.
Args:
key: Target numeric indices by which to retrieve data.
Returns:
A new Query Compiler.
"""
def get_row(df, key):
return df.iloc[key]
return DataFrameDefault.register(get_row)(self, key=key)
# END Abstract __getitem__ methods
# Abstract insert
# This method changes the shape of the resulting data. In Pandas, this
# operation is always inplace, but this object is immutable, so we just
# return a new one from here and let the front end handle the inplace
# update.
def insert(self, loc, column, value):
"""Insert new column data.
Args:
loc: Insertion index.
column: Column labels to insert.
value: Dtype object values to insert.
Returns:
A new QueryCompiler with new data inserted.
"""
return DataFrameDefault.register(pandas.DataFrame.insert, inplace=True)(
self, loc=loc, column=column, value=value
)