forked from modin-project/modin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.py
4377 lines (3994 loc) · 148 KB
/
base.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.
"""Implement DataFrame/Series public API as pandas does."""
from __future__ import annotations
import abc
import pickle as pkl
import re
import warnings
from functools import cached_property
from typing import (
TYPE_CHECKING,
Any,
Callable,
Hashable,
Literal,
Optional,
Sequence,
Union,
)
import numpy as np
import pandas
import pandas.core.generic
import pandas.core.resample
import pandas.core.window.rolling
from pandas._libs import lib
from pandas._libs.tslibs import to_offset
from pandas._typing import (
Axis,
CompressionOptions,
DtypeBackend,
IndexKeyFunc,
IndexLabel,
Level,
RandomState,
Scalar,
StorageOptions,
T,
TimedeltaConvertibleTypes,
TimestampConvertibleTypes,
npt,
)
from pandas.compat import numpy as numpy_compat
from pandas.core.common import count_not_none, pipe
from pandas.core.dtypes.common import (
is_bool_dtype,
is_dict_like,
is_dtype_equal,
is_integer,
is_integer_dtype,
is_list_like,
is_numeric_dtype,
is_object_dtype,
)
from pandas.core.indexes.api import ensure_index
from pandas.core.methods.describe import _refine_percentiles
from pandas.util._validators import (
validate_ascending,
validate_bool_kwarg,
validate_percentile,
)
from modin import pandas as pd
from modin.error_message import ErrorMessage
from modin.logging import ClassLogger, disable_logging
from modin.pandas.accessor import CachedAccessor, ModinAPI
from modin.pandas.utils import is_scalar
from modin.utils import _inherit_docstrings, expanduser_path_arg, try_cast_to_pandas
from .utils import _doc_binary_op, is_full_grab_slice
if TYPE_CHECKING:
from typing_extensions import Self
from modin.core.storage_formats import BaseQueryCompiler
from .dataframe import DataFrame
from .indexing import _iLocIndexer, _LocIndexer
from .resample import Resampler
from .series import Series
from .window import Expanding, Rolling, Window
# Similar to pandas, sentinel value to use as kwarg in place of None when None has
# special meaning and needs to be distinguished from a user explicitly passing None.
sentinel = object()
# Do not lookup certain attributes in columns or index, as they're used for some
# special purposes, like serving remote context
_ATTRS_NO_LOOKUP = {
"__name__",
"_cache",
"_ipython_canary_method_should_not_exist_",
"_ipython_display_",
"_repr_mimebundle_",
}
_DEFAULT_BEHAVIOUR = {
"__init__",
"__class__",
"_get_index",
"_set_index",
"_pandas_class",
"_get_axis_number",
"empty",
"index",
"columns",
"name",
"dtypes",
"dtype",
"groupby",
"_get_name",
"_set_name",
"_default_to_pandas",
"_query_compiler",
"_to_pandas",
"_repartition",
"_build_repr_df",
"_reduce_dimension",
"__repr__",
"__len__",
"__constructor__",
"_create_or_update_from_compiler",
"_update_inplace",
# for persistance support;
# see DataFrame methods docstrings for more
"_inflate_light",
"_inflate_full",
"__reduce__",
"__reduce_ex__",
"_init",
} | _ATTRS_NO_LOOKUP
_doc_binary_op_kwargs = {"returns": "BasePandasDataset", "left": "BasePandasDataset"}
def _get_repr_axis_label_indexer(labels, num_for_repr):
"""
Get the indexer for the given axis labels to be used for the repr.
Parameters
----------
labels : pandas.Index
The axis labels.
num_for_repr : int
The number of elements to display.
Returns
-------
slice or list
The indexer to use for the repr.
"""
if len(labels) <= num_for_repr:
return slice(None)
# At this point, the entire axis has len(labels) elements, and num_for_repr <
# len(labels). We want to select a pandas subframe containing elements such that:
# - the repr of the pandas subframe will be the same as the repr of the entire
# frame.
# - the pandas repr will not be able to show all the elements and will put an
# ellipsis in the middle
#
# We accomplish this by selecting some elements from the front and some from the
# back, with the front having at most 1 element more than the back. The total
# number of elements will be num_for_repr + 1.
if num_for_repr % 2 == 0:
# If num_for_repr is even, take an extra element from the front.
# The total number of elements we are selecting is (num_for_repr // 2) * 2 + 1
# = num_for_repr + 1
front_repr_num = num_for_repr // 2 + 1
back_repr_num = num_for_repr // 2
else:
# If num_for_repr is odd, take an extra element from both the front and the
# back. The total number of elements we are selecting is
# (num_for_repr // 2) * 2 + 1 + 1 = num_for_repr + 1
front_repr_num = num_for_repr // 2 + 1
back_repr_num = num_for_repr // 2 + 1
all_positions = range(len(labels))
return list(all_positions[:front_repr_num]) + (
[] if back_repr_num == 0 else list(all_positions[-back_repr_num:])
)
@_inherit_docstrings(pandas.DataFrame, apilink=["pandas.DataFrame", "pandas.Series"])
class BasePandasDataset(ClassLogger):
"""
Implement most of the common code that exists in DataFrame/Series.
Since both objects share the same underlying representation, and the algorithms
are the same, we use this object to define the general behavior of those objects
and then use those objects to define the output type.
"""
# Pandas class that we pretend to be; usually it has the same name as our class
# but lives in "pandas" namespace.
_pandas_class = pandas.core.generic.NDFrame
_query_compiler: BaseQueryCompiler
_siblings: list[BasePandasDataset]
@cached_property
def _is_dataframe(self) -> bool:
"""
Tell whether this is a dataframe.
Ideally, other methods of BasePandasDataset shouldn't care whether this
is a dataframe or a series, but sometimes we need to know. This method
is better than hasattr(self, "columns"), which for series will call
self.__getattr__("columns"), which requires materializing the index.
Returns
-------
bool : Whether this is a dataframe.
"""
return issubclass(self._pandas_class, pandas.DataFrame)
@abc.abstractmethod
def _create_or_update_from_compiler(
self, new_query_compiler: BaseQueryCompiler, inplace: bool = False
) -> Self | None:
"""
Return or update a ``DataFrame`` or ``Series`` with given `new_query_compiler`.
Parameters
----------
new_query_compiler : BaseQueryCompiler
QueryCompiler to use to manage the data.
inplace : bool, default: False
Whether or not to perform update or creation inplace.
Returns
-------
DataFrame, Series or None
None if update was done, ``DataFrame`` or ``Series`` otherwise.
"""
pass
def _add_sibling(self, sibling: BasePandasDataset) -> None:
"""
Add a DataFrame or Series object to the list of siblings.
Siblings are objects that share the same query compiler. This function is called
when a shallow copy is made.
Parameters
----------
sibling : BasePandasDataset
Dataset to add to siblings list.
"""
sibling._siblings = self._siblings + [self]
self._siblings += [sibling]
for sib in self._siblings:
sib._siblings += [sibling]
def _build_repr_df(
self, num_rows: int, num_cols: int
) -> pandas.DataFrame | pandas.Series:
"""
Build pandas DataFrame for string representation.
Parameters
----------
num_rows : int
Number of rows to show in string representation. If number of
rows in this dataset is greater than `num_rows` then half of
`num_rows` rows from the beginning and half of `num_rows` rows
from the end are shown.
num_cols : int
Number of columns to show in string representation. If number of
columns in this dataset is greater than `num_cols` then half of
`num_cols` columns from the beginning and half of `num_cols`
columns from the end are shown.
Returns
-------
pandas.DataFrame or pandas.Series
A pandas dataset with `num_rows` or fewer rows and `num_cols` or fewer columns.
"""
# Fast track for empty dataframe.
if len(self.index) == 0 or (self._is_dataframe and len(self.columns) == 0):
return pandas.DataFrame(
index=self.index,
columns=self.columns if self._is_dataframe else None,
)
row_indexer = _get_repr_axis_label_indexer(self.index, num_rows)
if self._is_dataframe:
indexer = row_indexer, _get_repr_axis_label_indexer(self.columns, num_cols)
else:
indexer = row_indexer
return self.iloc[indexer]._query_compiler.to_pandas()
def _update_inplace(self, new_query_compiler: BaseQueryCompiler) -> None:
"""
Update the current DataFrame inplace.
Parameters
----------
new_query_compiler : BaseQueryCompiler
The new QueryCompiler to use to manage the data.
"""
old_query_compiler = self._query_compiler
self._query_compiler = new_query_compiler
for sib in self._siblings:
sib._query_compiler = new_query_compiler
old_query_compiler.free()
def _validate_other(
self,
other,
axis,
dtype_check=False,
compare_index=False,
):
"""
Help to check validity of other in inter-df operations.
Parameters
----------
other : modin.pandas.BasePandasDataset
Another dataset to validate against `self`.
axis : {None, 0, 1}
Specifies axis along which to do validation. When `1` or `None`
is specified, validation is done along `index`, if `0` is specified
validation is done along `columns` of `other` frame.
dtype_check : bool, default: False
Validates that both frames have compatible dtypes.
compare_index : bool, default: False
Compare Index if True.
Returns
-------
BaseQueryCompiler or Any
Other frame if it is determined to be valid.
Raises
------
ValueError
If `other` is `Series` and its length is different from
length of `self` `axis`.
TypeError
If any validation checks fail.
"""
if isinstance(other, BasePandasDataset):
return other._query_compiler
if not is_list_like(other):
# We skip dtype checking if the other is a scalar. Note that pandas
# is_scalar can be misleading as it is False for almost all objects,
# even when those objects should be treated as scalars. See e.g.
# https://github.com/modin-project/modin/issues/5236. Therefore, we
# detect scalars by checking that `other` is neither a list-like nor
# another BasePandasDataset.
return other
axis = self._get_axis_number(axis) if axis is not None else 1
result = other
if axis == 0:
if len(other) != len(self._query_compiler.index):
raise ValueError(
f"Unable to coerce to Series, length must be {len(self._query_compiler.index)}: "
+ f"given {len(other)}"
)
else:
if len(other) != len(self._query_compiler.columns):
raise ValueError(
f"Unable to coerce to Series, length must be {len(self._query_compiler.columns)}: "
+ f"given {len(other)}"
)
if hasattr(other, "dtype"):
other_dtypes = [other.dtype] * len(other)
elif is_dict_like(other):
other_dtypes = [
other[label] if pandas.isna(other[label]) else type(other[label])
for label in self._get_axis(axis)
# The binary operation is applied for intersection of axis labels
# and dictionary keys. So filtering out extra keys.
if label in other
]
else:
other_dtypes = [x if pandas.isna(x) else type(x) for x in other]
if compare_index:
if not self.index.equals(other.index):
raise TypeError("Cannot perform operation with non-equal index")
# Do dtype checking.
if dtype_check:
self_dtypes = self._get_dtypes()
if is_dict_like(other):
# The binary operation is applied for the intersection of axis labels
# and dictionary keys. So filtering `self_dtypes` to match the `other`
# dictionary.
self_dtypes = [
dtype
for label, dtype in zip(self._get_axis(axis), self._get_dtypes())
if label in other
]
# TODO(https://github.com/modin-project/modin/issues/5239):
# this spuriously rejects other that is a list including some
# custom type that can be added to self's elements.
for self_dtype, other_dtype in zip(self_dtypes, other_dtypes):
if not (
(is_numeric_dtype(self_dtype) and is_numeric_dtype(other_dtype))
or (is_numeric_dtype(self_dtype) and pandas.isna(other_dtype))
or (is_object_dtype(self_dtype) and is_object_dtype(other_dtype))
or (
lib.is_np_dtype(self_dtype, "mM")
and lib.is_np_dtype(self_dtype, "mM")
)
or is_dtype_equal(self_dtype, other_dtype)
):
raise TypeError("Cannot do operation with improper dtypes")
return result
def _validate_function(self, func, on_invalid=None) -> None:
"""
Check the validity of the function which is intended to be applied to the frame.
Parameters
----------
func : object
on_invalid : callable(str, cls), optional
Function to call in case invalid `func` is met, `on_invalid` takes an error
message and an exception type as arguments. If not specified raise an
appropriate exception.
**Note:** This parameter is a hack to concord with pandas error types.
"""
def error_raiser(msg, exception=Exception):
raise exception(msg)
if on_invalid is None:
on_invalid = error_raiser
if isinstance(func, dict):
[self._validate_function(fn, on_invalid) for fn in func.values()]
return
# We also could validate this, but it may be quite expensive for lazy-frames
# if not all(idx in self._get_axis(axis) for idx in func.keys()):
# error_raiser("Invalid dict keys", KeyError)
if not is_list_like(func):
func = [func]
for fn in func:
if isinstance(fn, str):
if not (hasattr(self, fn) or hasattr(np, fn)):
on_invalid(
f"'{fn}' is not a valid function for '{type(self).__name__}' object",
AttributeError,
)
elif not callable(fn):
on_invalid(
f"One of the passed functions has an invalid type: {type(fn)}: {fn}, "
+ "only callable or string is acceptable.",
TypeError,
)
def _binary_op(self, op, other, **kwargs) -> Self:
"""
Do binary operation between two datasets.
Parameters
----------
op : str
Name of binary operation.
other : modin.pandas.BasePandasDataset
Second operand of binary operation.
**kwargs : dict
Additional parameters to binary operation.
Returns
-------
modin.pandas.BasePandasDataset
Result of binary operation.
"""
# _axis indicates the operator will use the default axis
if kwargs.pop("_axis", None) is None:
if kwargs.get("axis", None) is not None:
kwargs["axis"] = axis = self._get_axis_number(kwargs.get("axis", None))
else:
kwargs["axis"] = axis = 1
else:
axis = 0
if kwargs.get("level", None) is not None:
# Broadcast is an internally used argument
kwargs.pop("broadcast", None)
return self._default_to_pandas(
getattr(self._pandas_class, op), other, **kwargs
)
other = self._validate_other(other, axis, dtype_check=True)
exclude_list = [
"__add__",
"__radd__",
"__and__",
"__rand__",
"__or__",
"__ror__",
"__xor__",
"__rxor__",
]
if op in exclude_list:
kwargs.pop("axis")
new_query_compiler = getattr(self._query_compiler, op)(other, **kwargs)
return self._create_or_update_from_compiler(new_query_compiler)
def _default_to_pandas(self, op, *args, reason: str = None, **kwargs):
"""
Convert dataset to pandas type and call a pandas function on it.
Parameters
----------
op : str
Name of pandas function.
*args : list
Additional positional arguments to be passed to `op`.
reason : str, optional
**kwargs : dict
Additional keywords arguments to be passed to `op`.
Returns
-------
object
Result of operation.
"""
empty_self_str = "" if not self.empty else " for empty DataFrame"
ErrorMessage.default_to_pandas(
"`{}.{}`{}".format(
type(self).__name__,
op if isinstance(op, str) else op.__name__,
empty_self_str,
),
reason=reason,
)
args = try_cast_to_pandas(args)
kwargs = try_cast_to_pandas(kwargs)
pandas_obj = self._to_pandas()
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
if callable(op):
result = op(pandas_obj, *args, **kwargs)
elif isinstance(op, str):
# The inner `getattr` is ensuring that we are treating this object (whether
# it is a DataFrame, Series, etc.) as a pandas object. The outer `getattr`
# will get the operation (`op`) from the pandas version of the class and run
# it on the object after we have converted it to pandas.
attr = getattr(self._pandas_class, op)
if isinstance(attr, property):
result = getattr(pandas_obj, op)
else:
result = attr(pandas_obj, *args, **kwargs)
else:
ErrorMessage.catch_bugs_and_request_email(
failure_condition=True,
extra_log="{} is an unsupported operation".format(op),
)
if isinstance(result, pandas.DataFrame):
from .dataframe import DataFrame
return DataFrame(result)
elif isinstance(result, pandas.Series):
from .series import Series
return Series(result)
# inplace
elif result is None:
return self._create_or_update_from_compiler(
getattr(pd, type(pandas_obj).__name__)(pandas_obj)._query_compiler,
inplace=True,
)
else:
try:
if (
isinstance(result, (list, tuple))
and len(result) == 2
and isinstance(result[0], pandas.DataFrame)
):
# Some operations split the DataFrame into two (e.g. align). We need to wrap
# both of the returned results
if isinstance(result[1], pandas.DataFrame):
second = self.__constructor__(result[1])
else:
second = result[1]
return self.__constructor__(result[0]), second
else:
return result
except TypeError:
return result
@classmethod
def _get_axis_number(cls, axis) -> int:
"""
Convert axis name or number to axis index.
Parameters
----------
axis : int, str or pandas._libs.lib.NoDefault
Axis name ('index' or 'columns') or number to be converted to axis index.
Returns
-------
int
0 or 1 - axis index in the array of axes stored in the dataframe.
"""
if axis is lib.no_default:
axis = None
return cls._pandas_class._get_axis_number(axis) if axis is not None else 0
@cached_property
def __constructor__(self) -> type[Self]:
"""
Construct DataFrame or Series object depending on self type.
Returns
-------
modin.pandas.BasePandasDataset
Constructed object.
"""
return type(self)
def abs(self) -> Self: # noqa: RT01, D200
"""
Return a `BasePandasDataset` with absolute numeric value of each element.
"""
self._validate_dtypes(numeric_only=True)
return self.__constructor__(query_compiler=self._query_compiler.abs())
def _set_index(self, new_index) -> None:
"""
Set the index for this DataFrame.
Parameters
----------
new_index : pandas.Index
The new index to set this.
"""
self._query_compiler.index = new_index
def _get_index(self) -> pandas.Index:
"""
Get the index for this DataFrame.
Returns
-------
pandas.Index
The union of all indexes across the partitions.
"""
return self._query_compiler.index
index: pandas.Index = property(_get_index, _set_index)
def _get_axis(self, axis) -> pandas.Index:
"""
Return index labels of the specified axis.
Parameters
----------
axis : {0, 1}
Axis to return labels on.
0 is for index, when 1 is for columns.
Returns
-------
pandas.Index
"""
return self.index if axis == 0 else self.columns
def add(
self, other, axis="columns", level=None, fill_value=None
) -> Self: # noqa: PR01, RT01, D200
"""
Return addition of `BasePandasDataset` and `other`, element-wise (binary operator `add`).
"""
return self._binary_op(
"add", other, axis=axis, level=level, fill_value=fill_value
)
def aggregate(
self, func=None, axis=0, *args, **kwargs
) -> DataFrame | Series | Scalar: # noqa: PR01, RT01, D200
"""
Aggregate using one or more operations over the specified axis.
"""
axis = self._get_axis_number(axis)
result = None
if axis == 0:
result = self._aggregate(func, _axis=axis, *args, **kwargs)
# TODO: handle case when axis == 1
if result is None:
kwargs.pop("is_transform", None)
return self.apply(func, axis=axis, args=args, **kwargs)
return result
agg: DataFrame | Series | Scalar = aggregate
def _aggregate(self, func, *args, **kwargs):
"""
Aggregate using one or more operations over index axis.
Parameters
----------
func : function, str, list or dict
Function to use for aggregating the data.
*args : list
Positional arguments to pass to func.
**kwargs : dict
Keyword arguments to pass to func.
Returns
-------
scalar or BasePandasDataset
See Also
--------
aggregate : Aggregate along any axis.
"""
_axis = kwargs.pop("_axis", 0)
kwargs.pop("_level", None)
if isinstance(func, str):
kwargs.pop("is_transform", None)
return self._string_function(func, *args, **kwargs)
# Dictionaries have complex behavior because they can be renamed here.
elif func is None or isinstance(func, dict):
return self._default_to_pandas("agg", func, *args, **kwargs)
kwargs.pop("is_transform", None)
return self.apply(func, axis=_axis, args=args, **kwargs)
def _string_function(self, func, *args, **kwargs):
"""
Execute a function identified by its string name.
Parameters
----------
func : str
Function name to call on `self`.
*args : list
Positional arguments to pass to func.
**kwargs : dict
Keyword arguments to pass to func.
Returns
-------
object
Function result.
"""
assert isinstance(func, str)
f = getattr(self, func, None)
if f is not None:
if callable(f):
return f(*args, **kwargs)
assert len(args) == 0
assert (
len([kwarg for kwarg in kwargs if kwarg not in ["axis", "_level"]]) == 0
)
return f
f = getattr(np, func, None)
if f is not None:
return self._default_to_pandas("agg", func, *args, **kwargs)
raise ValueError("{} is an unknown string function".format(func))
def _get_dtypes(self) -> list:
"""
Get dtypes as list.
Returns
-------
list
Either a one-element list that contains `dtype` if object denotes a Series
or a list that contains `dtypes` if object denotes a DataFrame.
"""
if hasattr(self, "dtype"):
return [self.dtype]
else:
return list(self.dtypes)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=None,
fill_value=None,
method=lib.no_default,
limit=lib.no_default,
fill_axis=lib.no_default,
broadcast_axis=lib.no_default,
) -> tuple[Self, Self]: # noqa: PR01, RT01, D200
"""
Align two objects on their axes with the specified join method.
"""
if (
method is not lib.no_default
or limit is not lib.no_default
or fill_axis is not lib.no_default
):
warnings.warn(
"The 'method', 'limit', and 'fill_axis' keywords in "
+ f"{type(self).__name__}.align are deprecated and will be removed "
+ "in a future version. Call fillna directly on the returned objects "
+ "instead.",
FutureWarning,
)
if fill_axis is lib.no_default:
fill_axis = 0
if method is lib.no_default:
method = None
if limit is lib.no_default:
limit = None
if broadcast_axis is not lib.no_default:
msg = (
f"The 'broadcast_axis' keyword in {type(self).__name__}.align is "
+ "deprecated and will be removed in a future version."
)
if broadcast_axis is not None:
if self.ndim == 1 and other.ndim == 2:
msg += (
" Use left = DataFrame({col: left for col in right.columns}, "
+ "index=right.index) before calling `left.align(right)` instead."
)
elif self.ndim == 2 and other.ndim == 1:
msg += (
" Use right = DataFrame({col: right for col in left.columns}, "
+ "index=left.index) before calling `left.align(right)` instead"
)
warnings.warn(msg, FutureWarning)
else:
broadcast_axis = None
left, right = self._query_compiler.align(
other._query_compiler,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
return self.__constructor__(query_compiler=left), self.__constructor__(
query_compiler=right
)
@abc.abstractmethod
def _reduce_dimension(self, query_compiler: BaseQueryCompiler) -> Series | Scalar:
"""
Reduce the dimension of data from the `query_compiler`.
Parameters
----------
query_compiler : BaseQueryCompiler
Query compiler to retrieve the data.
Returns
-------
Series | Scalar
"""
pass
def all(
self, axis=0, bool_only=False, skipna=True, **kwargs
) -> Self: # noqa: PR01, RT01, D200
"""
Return whether all elements are True, potentially over an axis.
"""
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
if axis is not None:
axis = self._get_axis_number(axis)
if bool_only and axis == 0:
if hasattr(self, "dtype"):
raise NotImplementedError(
"{}.{} does not implement numeric_only.".format(
type(self).__name__, "all"
)
)
data_for_compute = self[self.columns[self.dtypes == np.bool_]]
return data_for_compute.all(
axis=axis, bool_only=False, skipna=skipna, **kwargs
)
return self._reduce_dimension(
self._query_compiler.all(
axis=axis, bool_only=bool_only, skipna=skipna, **kwargs
)
)
else:
if bool_only:
raise ValueError("Axis must be 0 or 1 (got {})".format(axis))
# Reduce to a scalar if axis is None.
result = self._reduce_dimension(
# FIXME: Judging by pandas docs `**kwargs` serves only compatibility
# purpose and does not affect the result, we shouldn't pass them to the query compiler.
self._query_compiler.all(
axis=0,
bool_only=bool_only,
skipna=skipna,
**kwargs,
)
)
if isinstance(result, BasePandasDataset):
return result.all(
axis=axis, bool_only=bool_only, skipna=skipna, **kwargs
)
return result
def any(
self, *, axis=0, bool_only=False, skipna=True, **kwargs
) -> Self: # noqa: PR01, RT01, D200
"""
Return whether any element is True, potentially over an axis.
"""
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
if axis is not None:
axis = self._get_axis_number(axis)
if bool_only and axis == 0:
if hasattr(self, "dtype"):
raise NotImplementedError(
"{}.{} does not implement numeric_only.".format(
type(self).__name__, "all"
)
)
data_for_compute = self[self.columns[self.dtypes == np.bool_]]
return data_for_compute.any(
axis=axis, bool_only=False, skipna=skipna, **kwargs
)
return self._reduce_dimension(
self._query_compiler.any(
axis=axis, bool_only=bool_only, skipna=skipna, **kwargs
)
)
else:
if bool_only:
raise ValueError("Axis must be 0 or 1 (got {})".format(axis))
# Reduce to a scalar if axis is None.
result = self._reduce_dimension(
self._query_compiler.any(
axis=0,
bool_only=bool_only,
skipna=skipna,
**kwargs,
)
)
if isinstance(result, BasePandasDataset):
return result.any(
axis=axis, bool_only=bool_only, skipna=skipna, **kwargs
)
return result
def apply(
self,
func,
axis,
raw,
result_type,
args,
**kwds,
) -> BaseQueryCompiler: # noqa: PR01, RT01, D200
"""
Apply a function along an axis of the `BasePandasDataset`.
"""
def error_raiser(msg, exception):
"""Convert passed exception to the same type as pandas do and raise it."""
# HACK: to concord with pandas error types by replacing all of the
# TypeErrors to the AssertionErrors
exception = exception if exception is not TypeError else AssertionError
raise exception(msg)
self._validate_function(func, on_invalid=error_raiser)
axis = self._get_axis_number(axis)
if isinstance(func, str):
# if axis != 1 function can be bounded to the Series, which doesn't
# support axis parameter
if axis == 1:
kwds["axis"] = axis
result = self._string_function(func, *args, **kwds)
if isinstance(result, BasePandasDataset):
return result._query_compiler
return result
elif isinstance(func, dict):
if len(self.columns) != len(set(self.columns)):
warnings.warn(
"duplicate column names not supported with apply().",
FutureWarning,
stacklevel=2,