/
base.py
4105 lines (3638 loc) · 142 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.
import os
import numpy as np
from numpy import nan
import pandas
from pandas.compat import numpy as numpy_compat
from pandas.core.common import count_not_none, pipe
from pandas.core.dtypes.common import (
is_list_like,
is_dict_like,
is_numeric_dtype,
is_datetime_or_timedelta_dtype,
is_dtype_equal,
is_object_dtype,
)
from pandas.core.indexing import convert_to_index_sliceable
from pandas.util._validators import validate_bool_kwarg, validate_percentile
from pandas._libs.lib import no_default
from pandas._typing import (
TimedeltaConvertibleTypes,
TimestampConvertibleTypes,
IndexKeyFunc,
)
import re
from typing import Optional, Union
import warnings
import pickle as pkl
from modin.utils import try_cast_to_pandas
from modin.error_message import ErrorMessage
from modin.pandas.utils import is_scalar
# 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 = {"____id_pack__", "__name__"}
class BasePandasDataset(object):
"""This object is the base for 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.
"""
# Siblings are other objects that share the same query compiler. We use this list
# to update inplace when there is a shallow copy.
_siblings = []
def _add_sibling(self, sibling):
sibling._siblings = self._siblings + [self]
self._siblings += [sibling]
for sib in self._siblings:
sib._siblings += [sibling]
def _build_repr_df(self, num_rows, num_cols):
# Fast track for empty dataframe.
if len(self.index) == 0 or (
hasattr(self, "columns") and len(self.columns) == 0
):
return pandas.DataFrame(
index=self.index,
columns=self.columns if hasattr(self, "columns") else None,
)
if len(self.index) <= num_rows:
row_indexer = slice(None)
else:
# Add one here so that pandas automatically adds the dots
# It turns out to be faster to extract 2 extra rows and columns than to
# build the dots ourselves.
num_rows_for_head = num_rows // 2 + 1
num_rows_for_tail = (
num_rows_for_head
if len(self.index) > num_rows
else len(self.index) - num_rows_for_head
if len(self.index) - num_rows_for_head >= 0
else None
)
row_indexer = list(range(len(self.index))[:num_rows_for_head]) + (
list(range(len(self.index))[-num_rows_for_tail:])
if num_rows_for_tail is not None
else []
)
if hasattr(self, "columns"):
if len(self.columns) <= num_cols:
col_indexer = slice(None)
else:
num_cols_for_front = num_cols // 2 + 1
num_cols_for_back = (
num_cols_for_front
if len(self.columns) > num_cols
else len(self.columns) - num_cols_for_front
if len(self.columns) - num_cols_for_front >= 0
else None
)
col_indexer = list(range(len(self.columns))[:num_cols_for_front]) + (
list(range(len(self.columns))[-num_cols_for_back:])
if num_cols_for_back is not None
else []
)
indexer = row_indexer, col_indexer
else:
indexer = row_indexer
return self.iloc[indexer]._query_compiler.to_pandas()
def _update_inplace(self, new_query_compiler):
"""Updates the current DataFrame inplace.
Args:
new_query_compiler: 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 _handle_level_agg(self, axis, level, op, sort=False, **kwargs):
"""Helper method to perform error checking for aggregation functions with a level parameter.
Args:
axis: The axis to apply the operation on
level: The level of the axis to apply the operation on
op: String representation of the operation to be performed on the level
"""
return getattr(self.groupby(level=level, axis=axis, sort=sort), op)(**kwargs)
def _validate_other(
self,
other,
axis,
numeric_only=False,
numeric_or_time_only=False,
numeric_or_object_only=False,
comparison_dtypes_only=False,
):
"""Helper method to check validity of other in inter-df operations"""
# We skip dtype checking if the other is a scalar.
if is_scalar(other):
return other
axis = self._get_axis_number(axis) if axis is not None else 1
result = other
if isinstance(other, BasePandasDataset):
return other._query_compiler
elif is_list_like(other):
if axis == 0:
if len(other) != len(self._query_compiler.index):
raise ValueError(
"Unable to coerce to Series, length must be {0}: "
"given {1}".format(len(self._query_compiler.index), len(other))
)
else:
if len(other) != len(self._query_compiler.columns):
raise ValueError(
"Unable to coerce to Series, length must be {0}: "
"given {1}".format(
len(self._query_compiler.columns), len(other)
)
)
if hasattr(other, "dtype"):
other_dtypes = [other.dtype] * len(other)
else:
other_dtypes = [type(x) for x in other]
else:
other_dtypes = [
type(other)
for _ in range(
len(self._query_compiler.index)
if axis
else len(self._query_compiler.columns)
)
]
# Do dtype checking.
if numeric_only:
if not all(
is_numeric_dtype(self_dtype) and is_numeric_dtype(other_dtype)
for self_dtype, other_dtype in zip(self._get_dtypes(), other_dtypes)
):
raise TypeError("Cannot do operation on non-numeric dtypes")
elif numeric_or_object_only:
if not all(
(is_numeric_dtype(self_dtype) and is_numeric_dtype(other_dtype))
or (is_object_dtype(self_dtype) and is_object_dtype(other_dtype))
for self_dtype, other_dtype in zip(self._get_dtypes(), other_dtypes)
):
raise TypeError("Cannot do operation non-numeric dtypes")
elif comparison_dtypes_only:
if not all(
(is_numeric_dtype(self_dtype) and is_numeric_dtype(other_dtype))
or (
is_datetime_or_timedelta_dtype(self_dtype)
and is_datetime_or_timedelta_dtype(other_dtype)
)
or is_dtype_equal(self_dtype, other_dtype)
for self_dtype, other_dtype in zip(self._get_dtypes(), other_dtypes)
):
raise TypeError(
"Cannot do operation non-numeric objects with numeric objects"
)
elif numeric_or_time_only:
if not all(
(is_numeric_dtype(self_dtype) and is_numeric_dtype(other_dtype))
or (
is_datetime_or_timedelta_dtype(self_dtype)
and is_datetime_or_timedelta_dtype(other_dtype)
)
for self_dtype, other_dtype in zip(self._get_dtypes(), other_dtypes)
):
raise TypeError(
"Cannot do operation non-numeric objects with numeric objects"
)
return result
def _binary_op(self, op, other, **kwargs):
# _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(getattr(pandas, type(self).__name__), op), other, **kwargs
)
other = self._validate_other(other, axis, numeric_or_object_only=True)
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, **kwargs):
"""Helper method to use default pandas function"""
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,
)
)
args = try_cast_to_pandas(args)
kwargs = try_cast_to_pandas(kwargs)
pandas_obj = self._to_pandas()
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.
result = getattr(getattr(pandas, type(self).__name__), op)(
pandas_obj, *args, **kwargs
)
else:
ErrorMessage.catch_bugs_and_request_email(
failure_condition=True,
extra_log="{} is an unsupported operation".format(op),
)
# SparseDataFrames cannot be serialized by arrow and cause problems for Modin.
# For now we will use pandas.
if isinstance(result, type(self)) and not isinstance(
result, (pandas.SparseDataFrame, pandas.SparseSeries)
):
return self._create_or_update_from_compiler(
result, inplace=kwargs.get("inplace", False)
)
elif 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:
import modin.pandas as pd
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
def _get_axis_number(self, axis):
return (
getattr(pandas, type(self).__name__)()._get_axis_number(axis)
if axis is not None
else 0
)
def __constructor__(self, *args, **kwargs):
return type(self)(*args, **kwargs)
def abs(self):
"""Apply an absolute value function to all numeric columns.
Returns:
A new DataFrame with the applied absolute value.
"""
self._validate_dtypes(numeric_only=True)
return self.__constructor__(query_compiler=self._query_compiler.abs())
def _set_index(self, new_index):
"""Set the index for this DataFrame.
Args:
new_index: The new index to set this
"""
self._query_compiler.index = new_index
def _get_index(self):
"""Get the index for this DataFrame.
Returns:
The union of all indexes across the partitions.
"""
return self._query_compiler.index
index = property(_get_index, _set_index)
def add(self, other, axis="columns", level=None, fill_value=None):
"""Add this DataFrame to another or a scalar/list.
Args:
other: What to add this this DataFrame.
axis: The axis to apply addition over. Only applicable to Series
or list 'other'.
level: A level in the multilevel axis to add over.
fill_value: The value to fill NaN.
Returns:
A new DataFrame with the applied addition.
"""
return self._binary_op(
"add", other, axis=axis, level=level, fill_value=fill_value
)
def aggregate(self, func=None, axis=0, *args, **kwargs):
warnings.warn(
"Modin index may not match pandas index due to pandas issue pandas-dev/pandas#36189."
)
axis = self._get_axis_number(axis)
result = None
if axis == 0:
try:
result = self._aggregate(func, _axis=axis, *args, **kwargs)
except TypeError:
pass
if result is None:
kwargs.pop("is_transform", None)
return self.apply(func, axis=axis, args=args, **kwargs)
return result
agg = aggregate
def _aggregate(self, arg, *args, **kwargs):
_axis = kwargs.pop("_axis", 0)
kwargs.pop("_level", None)
if isinstance(arg, str):
kwargs.pop("is_transform", None)
return self._string_function(arg, *args, **kwargs)
# Dictionaries have complex behavior because they can be renamed here.
elif isinstance(arg, dict):
return self._default_to_pandas("agg", arg, *args, **kwargs)
elif is_list_like(arg) or callable(arg):
kwargs.pop("is_transform", None)
return self.apply(arg, axis=_axis, args=args, **kwargs)
else:
raise TypeError("type {} is not callable".format(type(arg)))
def _string_function(self, func, *args, **kwargs):
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):
if hasattr(self, "dtype"):
return [self.dtype]
else:
return list(self.dtypes)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
):
return self._default_to_pandas(
"align",
other,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
"""Return whether all elements are True over requested axis
Note:
If axis=None or axis=0, this call applies df.all(axis=1)
to the transpose of df.
"""
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, level=level, **kwargs
)
if level is not None:
if bool_only is not None:
raise NotImplementedError(
"Option bool_only is not implemented with option level."
)
return self._handle_level_agg(
axis, level, "all", skipna=skipna, **kwargs
)
return self._reduce_dimension(
self._query_compiler.all(
axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs
)
)
else:
if bool_only:
raise ValueError("Axis must be 0 or 1 (got {})".format(axis))
# Reduce to a scalar if axis is None.
if level is not None:
return self._handle_level_agg(
axis, level, "all", skipna=skipna, **kwargs
)
else:
result = self._reduce_dimension(
self._query_compiler.all(
axis=0,
bool_only=bool_only,
skipna=skipna,
level=level,
**kwargs,
)
)
if isinstance(result, BasePandasDataset):
return result.all(
axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs
)
return result
def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
"""Return whether any elements are True over requested axis
Note:
If axis=None or axis=0, this call applies on the column partitions,
otherwise operates on row partitions
"""
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, level=level, **kwargs
)
if level is not None:
if bool_only is not None:
raise NotImplementedError(
"Option bool_only is not implemented with option level."
)
return self._handle_level_agg(
axis, level, "any", skipna=skipna, **kwargs
)
return self._reduce_dimension(
self._query_compiler.any(
axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs
)
)
else:
if bool_only:
raise ValueError("Axis must be 0 or 1 (got {})".format(axis))
# Reduce to a scalar if axis is None.
if level is not None:
return self._handle_level_agg(
axis, level, "any", skipna=skipna, **kwargs
)
else:
result = self._reduce_dimension(
self._query_compiler.any(
axis=0,
bool_only=bool_only,
skipna=skipna,
level=level,
**kwargs,
)
)
if isinstance(result, BasePandasDataset):
return result.any(
axis=axis, bool_only=bool_only, skipna=skipna, level=level, **kwargs
)
return result
def apply(
self,
func,
axis=0,
broadcast=None,
raw=False,
reduce=None,
result_type=None,
convert_dtype=True,
args=(),
**kwds,
):
"""Apply a function along input axis of DataFrame.
Args:
func: The function to apply
axis: The axis over which to apply the func.
broadcast: Whether or not to broadcast.
raw: Whether or not to convert to a Series.
reduce: Whether or not to try to apply reduction procedures.
Returns:
Series or DataFrame, depending on func.
"""
warnings.warn(
"Modin index may not match pandas index due to pandas issue pandas-dev/pandas#36189."
)
axis = self._get_axis_number(axis)
ErrorMessage.non_verified_udf()
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 axis == 1:
raise TypeError(
"(\"'dict' object is not callable\", "
"'occurred at index {0}'".format(self.index[0])
)
if len(self.columns) != len(set(self.columns)):
warnings.warn(
"duplicate column names not supported with apply().",
FutureWarning,
stacklevel=2,
)
elif not callable(func) and not is_list_like(func):
raise TypeError("{} object is not callable".format(type(func)))
query_compiler = self._query_compiler.apply(
func,
axis,
args=args,
raw=raw,
result_type=result_type,
**kwds,
)
return query_compiler
def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None):
return self._default_to_pandas(
"asfreq",
freq,
method=method,
how=how,
normalize=normalize,
fill_value=fill_value,
)
def asof(self, where, subset=None):
scalar = not is_list_like(where)
if isinstance(where, pandas.Index):
# Prevent accidental mutation of original:
where = where.copy()
else:
if scalar:
where = [where]
where = pandas.Index(where)
if subset is None:
data = self
else:
# Only relevant for DataFrames:
data = self[subset]
no_na_index = data.dropna().index
new_index = pandas.Index([no_na_index.asof(i) for i in where])
result = self.reindex(new_index)
result.index = where
if scalar:
# Need to return a Series:
result = result.squeeze()
return result
def astype(self, dtype, copy=True, errors="raise"):
col_dtypes = {}
if isinstance(dtype, dict):
if (
not set(dtype.keys()).issubset(set(self._query_compiler.columns))
and errors == "raise"
):
raise KeyError(
"Only a column name can be used for the key in"
"a dtype mappings argument."
)
col_dtypes = dtype
else:
for column in self._query_compiler.columns:
col_dtypes[column] = dtype
new_query_compiler = self._query_compiler.astype(col_dtypes)
return self._create_or_update_from_compiler(new_query_compiler, not copy)
@property
def at(self, axis=None):
from .indexing import _LocIndexer
return _LocIndexer(self)
def at_time(self, time, asof=False, axis=None):
axis = self._get_axis_number(axis)
if axis == 0:
return self.iloc[self.index.indexer_at_time(time, asof=asof)]
return self.iloc[:, self.columns.indexer_at_time(time, asof=asof)]
def between_time(
self, start_time, end_time, include_start=True, include_end=True, axis=None
):
axis = self._get_axis_number(axis)
idx = self.index if axis == 0 else self.columns
indexer = idx.indexer_between_time(
start_time, end_time, include_start=include_start, include_end=include_end
)
return self.iloc[indexer] if axis == 0 else self.iloc[:, indexer]
def bfill(self, axis=None, inplace=False, limit=None, downcast=None):
"""Synonym for DataFrame.fillna(method='bfill')"""
return self.fillna(
method="bfill", axis=axis, limit=limit, downcast=downcast, inplace=inplace
)
backfill = bfill
def bool(self):
"""Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
shape = self.shape
if shape != (1,) and shape != (1, 1):
raise ValueError(
"""The PandasObject does not have exactly
1 element. Return the bool of a single
element PandasObject. The truth value is
ambiguous. Use a.empty, a.item(), a.any()
or a.all()."""
)
else:
return self._to_pandas().bool()
def clip(self, lower=None, upper=None, axis=None, inplace=False, *args, **kwargs):
# validate inputs
if axis is not None:
axis = self._get_axis_number(axis)
self._validate_dtypes(numeric_only=True)
if is_list_like(lower) or is_list_like(upper):
if axis is None:
raise ValueError("Must specify axis = 0 or 1")
self._validate_other(lower, axis)
self._validate_other(upper, axis)
inplace = validate_bool_kwarg(inplace, "inplace")
axis = numpy_compat.function.validate_clip_with_axis(axis, args, kwargs)
# any np.nan bounds are treated as None
if lower is not None and np.any(np.isnan(lower)):
lower = None
if upper is not None and np.any(np.isnan(upper)):
upper = None
new_query_compiler = self._query_compiler.clip(
lower=lower, upper=upper, axis=axis, inplace=inplace, *args, **kwargs
)
return self._create_or_update_from_compiler(new_query_compiler, inplace)
def combine(self, other, func, fill_value=None, **kwargs):
return self._binary_op(
"combine", other, _axis=0, func=func, fill_value=fill_value, **kwargs
)
def combine_first(self, other):
return self._binary_op("combine_first", other, _axis=0)
def copy(self, deep=True):
"""Creates a shallow copy of the DataFrame.
Returns:
A new DataFrame pointing to the same partitions as this one.
"""
if deep:
return self.__constructor__(query_compiler=self._query_compiler.copy())
new_obj = self.__constructor__(query_compiler=self._query_compiler)
self._add_sibling(new_obj)
return new_obj
def count(self, axis=0, level=None, numeric_only=False):
"""Get the count of non-null objects in the DataFrame.
Arguments:
axis: 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
level: If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a DataFrame.
numeric_only: Include only float, int, boolean data
Returns:
The count, in a Series (or DataFrame if level is specified).
"""
axis = self._get_axis_number(axis)
if numeric_only is not None and numeric_only:
self._validate_dtypes(numeric_only=numeric_only)
if level is not None:
if not self._query_compiler.has_multiindex(axis=axis):
# error thrown by pandas
raise TypeError("Can only count levels on hierarchical columns.")
return self._handle_level_agg(axis=axis, level=level, op="count", sort=True)
return self._reduce_dimension(
self._query_compiler.count(
axis=axis, level=level, numeric_only=numeric_only
)
)
def cummax(self, axis=None, skipna=True, *args, **kwargs):
"""Perform a cumulative maximum across the DataFrame.
Args:
axis (int): The axis to take maximum on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative maximum of the DataFrame.
"""
axis = self._get_axis_number(axis)
if axis == 1:
self._validate_dtypes(numeric_only=True)
return self.__constructor__(
query_compiler=self._query_compiler.cummax(
axis=axis, skipna=skipna, **kwargs
)
)
def cummin(self, axis=None, skipna=True, *args, **kwargs):
"""Perform a cumulative minimum across the DataFrame.
Args:
axis (int): The axis to cummin on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative minimum of the DataFrame.
"""
axis = self._get_axis_number(axis)
if axis == 1:
self._validate_dtypes(numeric_only=True)
return self.__constructor__(
query_compiler=self._query_compiler.cummin(
axis=axis, skipna=skipna, **kwargs
)
)
def cumprod(self, axis=None, skipna=True, *args, **kwargs):
"""Perform a cumulative product across the DataFrame.
Args:
axis (int): The axis to take product on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative product of the DataFrame.
"""
axis = self._get_axis_number(axis)
self._validate_dtypes(numeric_only=True)
return self.__constructor__(
query_compiler=self._query_compiler.cumprod(
axis=axis, skipna=skipna, **kwargs
)
)
def cumsum(self, axis=None, skipna=True, *args, **kwargs):
"""Perform a cumulative sum across the DataFrame.
Args:
axis (int): The axis to take sum on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative sum of the DataFrame.
"""
axis = self._get_axis_number(axis)
self._validate_dtypes(numeric_only=True)
return self.__constructor__(
query_compiler=self._query_compiler.cumsum(
axis=axis, skipna=skipna, **kwargs
)
)
def describe(
self, percentiles=None, include=None, exclude=None, datetime_is_numeric=False
):
"""
Generates descriptive statistics that summarize the central tendency,
dispersion and shape of a dataset's distribution, excluding NaN values.
Args:
percentiles (list-like of numbers, optional):
The percentiles to include in the output.
include: White-list of data types to include in results
exclude: Black-list of data types to exclude in results
datetime_is_numeric : bool, default False
Whether to treat datetime dtypes as numeric.
This affects statistics calculated for the column. For DataFrame input,
this also controls whether datetime columns are included by default.
Returns: Series/DataFrame of summary statistics
"""
if include is not None and (isinstance(include, np.dtype) or include != "all"):
if not is_list_like(include):
include = [include]
include = [
np.dtype(i)
if not (isinstance(i, type) and i.__module__ == "numpy")
else i
for i in include
]
if not any(
(isinstance(inc, np.dtype) and inc == d)
or (
not isinstance(inc, np.dtype)
and inc.__subclasscheck__(getattr(np, d.__str__()))
)
for d in self._get_dtypes()
for inc in include
):
# This is the error that pandas throws.
raise ValueError("No objects to concatenate")
if exclude is not None:
if not is_list_like(exclude):
exclude = [exclude]
exclude = [np.dtype(e) for e in exclude]
if all(
(isinstance(exc, np.dtype) and exc == d)
or (
not isinstance(exc, np.dtype)
and exc.__subclasscheck__(getattr(np, d.__str__()))
)
for d in self._get_dtypes()
for exc in exclude
):
# This is the error that pandas throws.
raise ValueError("No objects to concatenate")
if percentiles is not None:
# explicit conversion of `percentiles` to list
percentiles = list(percentiles)
# get them all to be in [0, 1]
validate_percentile(percentiles)
# median should always be included
if 0.5 not in percentiles:
percentiles.append(0.5)
percentiles = np.asarray(percentiles)
else:
percentiles = np.array([0.25, 0.5, 0.75])
return self.__constructor__(
query_compiler=self._query_compiler.describe(
percentiles=percentiles,
include=include,
exclude=exclude,
datetime_is_numeric=datetime_is_numeric,
)
)
def diff(self, periods=1, axis=0):
"""Finds the difference between elements on the axis requested
Args:
periods: Periods to shift for forming difference
axis: Take difference over rows or columns
Returns:
DataFrame with the diff applied
"""
axis = self._get_axis_number(axis)
return self.__constructor__(
query_compiler=self._query_compiler.diff(periods=periods, axis=axis)
)
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
"""Return new object with labels in requested axis removed.
Args:
labels: Index or column labels to drop.
axis: Whether to drop labels from the index (0 / 'index') or
columns (1 / 'columns').
index, columns: Alternative to specifying axis (labels, axis=1 is
equivalent to columns=labels).
level: For MultiIndex
inplace: If True, do operation inplace and return None.
errors: If 'ignore', suppress error and existing labels are
dropped.
Returns:
dropped : type of caller
"""
# TODO implement level
if level is not None:
return self._default_to_pandas(
"drop",