-
Notifications
You must be signed in to change notification settings - Fork 647
/
series.py
1708 lines (1457 loc) · 53.9 KB
/
series.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 Series public API as Pandas does.
Almost all docstrings for public and magic methods should be inherited from Pandas
for better maintability. So some codes are ignored in pydocstyle check:
- D101: missing docstring in class
- D102: missing docstring in public method
- D105: missing docstring in magic method
Manually add documentation for methods which are not presented in pandas.
"""
import numpy as np
import pandas
from pandas.core.common import apply_if_callable, is_bool_indexer
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.common import (
is_dict_like,
is_list_like,
)
from pandas._libs.lib import no_default
from pandas._typing import IndexKeyFunc
import sys
from typing import Union, Optional
import warnings
from modin.utils import _inherit_docstrings, to_pandas
from modin.config import IsExperimental
from .base import BasePandasDataset, _ATTRS_NO_LOOKUP
from .iterator import PartitionIterator
from .utils import from_pandas, is_scalar
from .accessor import CachedAccessor, SparseAccessor
@_inherit_docstrings(pandas.Series, excluded=[pandas.Series.__init__])
class Series(BasePandasDataset):
def __init__(
self,
data=None,
index=None,
dtype=None,
name=None,
copy=False,
fastpath=False,
query_compiler=None,
):
"""
One-dimensional ndarray with axis labels (including time series).
TODO: add types.
Parameters
----------
data:
Contains data stored in Series.
index:
Values must be hashable and have the same length as `data`.
dtype:
Data type for the output Series. If not specified, this will be
inferred from `data`.
name:
The name to give to the Series.
copy:
Copy input data.
query_compiler: query_compiler
A query compiler object to create the Series from.
"""
if isinstance(data, type(self)):
query_compiler = data._query_compiler.copy()
if index is not None:
if any(i not in data.index for i in index):
raise NotImplementedError(
"Passing non-existent columns or index values to constructor "
"not yet implemented."
)
query_compiler = data.loc[index]._query_compiler
if query_compiler is None:
# Defaulting to pandas
warnings.warn(
"Distributing {} object. This may take some time.".format(type(data))
)
if name is None:
name = "__reduced__"
if isinstance(data, pandas.Series) and data.name is not None:
name = data.name
query_compiler = from_pandas(
pandas.DataFrame(
pandas.Series(
data=data,
index=index,
dtype=dtype,
name=name,
copy=copy,
fastpath=fastpath,
)
)
)._query_compiler
self._query_compiler = query_compiler.columnarize()
if name is not None:
self._query_compiler = self._query_compiler
self.name = name
def _get_name(self):
name = self._query_compiler.columns[0]
if name == "__reduced__":
return None
return name
def _set_name(self, name):
if name is None:
name = "__reduced__"
self._query_compiler.columns = [name]
name = property(_get_name, _set_name)
_parent = None
# Parent axis denotes axis that was used to select series in a parent dataframe.
# If _parent_axis == 0, then it means that index axis was used via df.loc[row]
# indexing operations and assignments should be done to rows of parent.
# If _parent_axis == 1 it means that column axis was used via df[column] and assignments
# should be done to columns of parent.
_parent_axis = 0
def __add__(self, right):
return self.add(right)
def __radd__(self, left):
return self.add(left)
def __and__(self, other):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).__and__(new_other)
def __array__(self, dtype=None):
return super(Series, self).__array__(dtype).flatten()
@property
def __array_priority__(self): # pragma: no cover
return self._to_pandas().__array_priority__
def __bytes__(self):
return self._default_to_pandas(pandas.Series.__bytes__)
def __contains__(self, key):
return key in self.index
def __copy__(self, deep=True):
return self.copy(deep=deep)
def __deepcopy__(self, memo=None):
return self.copy(deep=True)
def __delitem__(self, key):
if key not in self.keys():
raise KeyError(key)
self.drop(labels=key, inplace=True)
def __div__(self, right):
return self.div(right)
def __rdiv__(self, left):
return self.rdiv(left)
def __divmod__(self, right):
return self.divmod(right)
def __rdivmod__(self, left):
return self.rdivmod(left)
def __float__(self):
return float(self.squeeze())
def __floordiv__(self, right):
return self.floordiv(right)
def __rfloordiv__(self, right):
return self.rfloordiv(right)
def __getattr__(self, key):
try:
return object.__getattribute__(self, key)
except AttributeError as e:
if key not in _ATTRS_NO_LOOKUP and key in self.index:
return self[key]
raise e
def __int__(self):
return int(self.squeeze())
def __iter__(self):
return self._to_pandas().__iter__()
def __mod__(self, right):
return self.mod(right)
def __rmod__(self, left):
return self.rmod(left)
def __mul__(self, right):
return self.mul(right)
def __rmul__(self, left):
return self.rmul(left)
def __or__(self, other):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).__or__(new_other)
def __pow__(self, right):
return self.pow(right)
def __rpow__(self, left):
return self.rpow(left)
def __repr__(self):
num_rows = pandas.get_option("max_rows") or 60
num_cols = pandas.get_option("max_columns") or 20
temp_df = self._build_repr_df(num_rows, num_cols)
if isinstance(temp_df, pandas.DataFrame) and not temp_df.empty:
temp_df = temp_df.iloc[:, 0]
temp_str = repr(temp_df)
freq_str = (
"Freq: {}, ".format(self.index.freqstr)
if isinstance(self.index, pandas.DatetimeIndex)
else ""
)
if self.name is not None:
name_str = "Name: {}, ".format(str(self.name))
else:
name_str = ""
if len(self.index) > num_rows:
len_str = "Length: {}, ".format(len(self.index))
else:
len_str = ""
dtype_str = "dtype: {}".format(
str(self.dtype) + ")"
if temp_df.empty
else temp_str.rsplit("dtype: ", 1)[-1]
)
if len(self) == 0:
return "Series([], {}{}{}".format(freq_str, name_str, dtype_str)
return temp_str.rsplit("\n", 1)[0] + "\n{}{}{}{}".format(
freq_str, name_str, len_str, dtype_str
)
def __round__(self, decimals=0):
return self._create_or_update_from_compiler(
self._query_compiler.round(decimals=decimals)
)
def __setitem__(self, key, value):
if key not in self.keys():
raise KeyError(key)
self._create_or_update_from_compiler(
self._query_compiler.setitem(1, key, value), inplace=True
)
def __sub__(self, right):
return self.sub(right)
def __rsub__(self, left):
return self.rsub(left)
def __truediv__(self, right):
return self.truediv(right)
def __rtruediv__(self, left):
return self.rtruediv(left)
__iadd__ = __add__
__imul__ = __add__
__ipow__ = __pow__
__isub__ = __sub__
__itruediv__ = __truediv__
@property
def values(self):
return super(Series, self).to_numpy().flatten()
def __xor__(self, other):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).__xor__(new_other)
def add(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).add(
new_other, level=level, fill_value=fill_value, axis=axis
)
def add_prefix(self, prefix):
return Series(query_compiler=self._query_compiler.add_prefix(prefix, axis=0))
def add_suffix(self, suffix):
return Series(query_compiler=self._query_compiler.add_suffix(suffix, axis=0))
def append(self, to_append, ignore_index=False, verify_integrity=False):
from .dataframe import DataFrame
bad_type_msg = (
'cannot concatenate object of type "{}"; only pd.Series, '
"pd.DataFrame, and pd.Panel (deprecated) objs are valid"
)
if isinstance(to_append, list):
if not all(isinstance(o, BasePandasDataset) for o in to_append):
raise TypeError(
bad_type_msg.format(
type(
next(
o
for o in to_append
if not isinstance(o, BasePandasDataset)
)
)
)
)
elif all(isinstance(o, Series) for o in to_append):
self.name = None
for i in range(len(to_append)):
to_append[i].name = None
to_append[i] = to_append[i]._query_compiler
else:
# Matching pandas behavior of naming the Series columns 0
self.name = 0
for i in range(len(to_append)):
if isinstance(to_append[i], Series):
to_append[i].name = 0
to_append[i] = DataFrame(to_append[i])
return DataFrame(self.copy()).append(
to_append,
ignore_index=ignore_index,
verify_integrity=verify_integrity,
)
elif isinstance(to_append, Series):
self.name = None
to_append.name = None
to_append = [to_append._query_compiler]
elif isinstance(to_append, DataFrame):
self.name = 0
return DataFrame(self.copy()).append(
to_append, ignore_index=ignore_index, verify_integrity=verify_integrity
)
else:
raise TypeError(bad_type_msg.format(type(to_append)))
# If ignore_index is False, by definition the Index will be correct.
# We also do this first to ensure that we don't waste compute/memory.
if verify_integrity and not ignore_index:
appended_index = (
self.index.append(to_append.index)
if not isinstance(to_append, list)
else self.index.append([o.index for o in to_append])
)
is_valid = next((False for idx in appended_index.duplicated() if idx), True)
if not is_valid:
raise ValueError(
"Indexes have overlapping values: {}".format(
appended_index[appended_index.duplicated()]
)
)
query_compiler = self._query_compiler.concat(
0, to_append, ignore_index=ignore_index, sort=None
)
if len(query_compiler.columns) > 1:
return DataFrame(query_compiler=query_compiler)
else:
return Series(query_compiler=query_compiler)
def apply(self, func, convert_dtype=True, args=(), **kwds):
# apply and aggregate have slightly different behaviors, so we have to use
# each one separately to determine the correct return type. In the case of
# `agg`, the axis is set, but it is not required for the computation, so we use
# it to determine which function to run.
if kwds.pop("axis", None) is not None:
apply_func = "agg"
else:
apply_func = "apply"
# This is the simplest way to determine the return type, but there are checks
# in pandas that verify that some results are created. This is a challenge for
# empty DataFrames, but fortunately they only happen when the `func` type is
# a list or a dictionary, which means that the return type won't change from
# type(self), so we catch that error and use `type(self).__name__` for the return
# type.
# We create a "dummy" `Series` to do the error checking and determining
# the return type.
try:
return_type = type(
getattr(pandas.Series("", index=self.index[:1]), apply_func)(
func, *args, **kwds
)
).__name__
except Exception:
try:
return_type = type(
getattr(pandas.Series(0, index=self.index[:1]), apply_func)(
func, *args, **kwds
)
).__name__
except Exception:
return_type = type(self).__name__
if (
isinstance(func, str)
or is_list_like(func)
or return_type not in ["DataFrame", "Series"]
):
result = super(Series, self).apply(func, *args, **kwds)
else:
# handle ufuncs and lambdas
if kwds or args and not isinstance(func, np.ufunc):
def f(x):
return func(x, *args, **kwds)
else:
f = func
with np.errstate(all="ignore"):
if isinstance(f, np.ufunc):
return f(self)
result = self.map(f)._query_compiler
if return_type not in ["DataFrame", "Series"]:
# sometimes result can be not a query_compiler, but scalar (for example
# for sum or count functions)
if isinstance(result, type(self._query_compiler)):
return result.to_pandas().squeeze()
else:
return result
else:
result = getattr(sys.modules[self.__module__], return_type)(
query_compiler=result
)
if result.name == self.index[0]:
result.name = None
return result
def argmax(self, axis=None, skipna=True, *args, **kwargs):
result = self.idxmax(axis=axis, skipna=skipna, *args, **kwargs)
if np.isnan(result) or result is pandas.NA:
result = -1
return result
def argmin(self, axis=None, skipna=True, *args, **kwargs):
result = self.idxmin(axis=axis, skipna=skipna, *args, **kwargs)
if np.isnan(result) or result is pandas.NA:
result = -1
return result
def argsort(self, axis=0, kind="quicksort", order=None):
return self._default_to_pandas(
pandas.Series.argsort, axis=axis, kind=kind, order=order
)
def autocorr(self, lag=1):
return self.corr(self.shift(lag))
def between(self, left, right, inclusive=True):
return self._default_to_pandas(
pandas.Series.between, left, right, inclusive=inclusive
)
def combine(self, other, func, fill_value=None):
return super(Series, self).combine(
other, lambda s1, s2: s1.combine(s2, func, fill_value=fill_value)
)
def compare(
self,
other: "Series",
align_axis: Union[str, int] = 1,
keep_shape: bool = False,
keep_equal: bool = False,
):
return self._default_to_pandas(
pandas.Series.compare,
other=other,
align_axis=align_axis,
keep_shape=keep_shape,
keep_equal=keep_equal,
)
def corr(self, other, method="pearson", min_periods=None):
if method == "pearson":
this, other = self.align(other, join="inner", copy=False)
this = self.__constructor__(this)
other = self.__constructor__(other)
if len(this) == 0:
return np.nan
if len(this) != len(other):
raise ValueError("Operands must have same size")
if min_periods is None:
min_periods = 1
valid = this.notna() & other.notna()
if not valid.all():
this = this[valid]
other = other[valid]
if len(this) < min_periods:
return np.nan
this = this.astype(dtype="float64")
other = other.astype(dtype="float64")
this -= this.mean()
other -= other.mean()
other = other.__constructor__(query_compiler=other._query_compiler.conj())
result = this * other / (len(this) - 1)
result = np.array([result.sum()])
stddev_this = ((this * this) / (len(this) - 1)).sum()
stddev_other = ((other * other) / (len(other) - 1)).sum()
stddev_this = np.array([np.sqrt(stddev_this)])
stddev_other = np.array([np.sqrt(stddev_other)])
result /= stddev_this * stddev_other
np.clip(result.real, -1, 1, out=result.real)
if np.iscomplexobj(result):
np.clip(result.imag, -1, 1, out=result.imag)
return result[0]
return self.__constructor__(
query_compiler=self._query_compiler.default_to_pandas(
pandas.Series.corr,
other._query_compiler,
method=method,
min_periods=min_periods,
)
)
def count(self, level=None):
return super(Series, self).count(level=level)
def cov(self, other, min_periods=None, ddof: Optional[int] = 1):
this, other = self.align(other, join="inner", copy=False)
this = self.__constructor__(this)
other = self.__constructor__(other)
if len(this) == 0:
return np.nan
if len(this) != len(other):
raise ValueError("Operands must have same size")
if min_periods is None:
min_periods = 1
valid = this.notna() & other.notna()
if not valid.all():
this = this[valid]
other = other[valid]
if len(this) < min_periods:
return np.nan
this = this.astype(dtype="float64")
other = other.astype(dtype="float64")
this -= this.mean()
other -= other.mean()
other = other.__constructor__(query_compiler=other._query_compiler.conj())
result = this * other / (len(this) - ddof)
result = result.sum()
return result
def describe(
self, percentiles=None, include=None, exclude=None, datetime_is_numeric=False
):
# Pandas ignores the `include` and `exclude` for Series for some reason.
return super(Series, self).describe(
percentiles=percentiles, datetime_is_numeric=datetime_is_numeric
)
def diff(self, periods=1):
return super(Series, self).diff(periods=periods, axis=0)
def divmod(self, other, level=None, fill_value=None, axis=0):
return self._default_to_pandas(
pandas.Series.divmod, other, level=level, fill_value=fill_value, axis=axis
)
def dot(self, other):
if isinstance(other, BasePandasDataset):
common = self.index.union(other.index)
if len(common) > len(self.index) or len(common) > len(other.index):
raise ValueError("Matrices are not aligned")
qc = other.reindex(index=common)._query_compiler
if isinstance(other, Series):
return self._reduce_dimension(
query_compiler=self._query_compiler.dot(
qc, squeeze_self=True, squeeze_other=True
)
)
else:
return self.__constructor__(
query_compiler=self._query_compiler.dot(
qc, squeeze_self=True, squeeze_other=False
)
)
other = np.asarray(other)
if self.shape[0] != other.shape[0]:
raise ValueError(
"Dot product shape mismatch, {} vs {}".format(self.shape, other.shape)
)
if len(other.shape) > 1:
return (
self._query_compiler.dot(other, squeeze_self=True).to_numpy().squeeze()
)
return self._reduce_dimension(
query_compiler=self._query_compiler.dot(other, squeeze_self=True)
)
def drop_duplicates(self, keep="first", inplace=False):
return super(Series, self).drop_duplicates(keep=keep, inplace=inplace)
def dropna(self, axis=0, inplace=False, how=None):
return super(Series, self).dropna(axis=axis, inplace=inplace)
def duplicated(self, keep="first"):
return self.to_frame().duplicated(keep=keep)
def eq(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).eq(new_other, level=level, axis=axis)
def equals(self, other):
return (
self.name == other.name
and self.index.equals(other.index)
and self.eq(other).all()
)
def explode(self, ignore_index: bool = False):
return self._default_to_pandas(pandas.Series.explode, ignore_index=ignore_index)
def factorize(self, sort=False, na_sentinel=-1):
return self._default_to_pandas(
pandas.Series.factorize, sort=sort, na_sentinel=na_sentinel
)
def floordiv(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).floordiv(
new_other, level=level, fill_value=None, axis=axis
)
def ge(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).ge(new_other, level=level, axis=axis)
def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=True,
group_keys=True,
squeeze: bool = no_default,
observed=False,
dropna: bool = True,
):
if squeeze is not no_default:
warnings.warn(
(
"The `squeeze` parameter is deprecated and "
"will be removed in a future version."
),
FutureWarning,
stacklevel=2,
)
else:
squeeze = False
from .groupby import SeriesGroupBy
if not as_index:
raise TypeError("as_index=False only valid with DataFrame")
# SeriesGroupBy expects a query compiler object if it is available
if isinstance(by, Series):
by = by._query_compiler
elif callable(by):
by = by(self.index)
elif by is None and level is None:
raise TypeError("You have to supply one of 'by' and 'level'")
return SeriesGroupBy(
self,
by,
axis,
level,
as_index,
sort,
group_keys,
squeeze,
idx_name=None,
observed=observed,
drop=False,
dropna=dropna,
)
def gt(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).gt(new_other, level=level, axis=axis)
def hist(
self,
by=None,
ax=None,
grid=True,
xlabelsize=None,
xrot=None,
ylabelsize=None,
yrot=None,
figsize=None,
bins=10,
**kwds,
):
return self._default_to_pandas(
pandas.Series.hist,
by=by,
ax=ax,
grid=grid,
xlabelsize=xlabelsize,
xrot=xrot,
ylabelsize=ylabelsize,
yrot=yrot,
figsize=figsize,
bins=bins,
**kwds,
)
def idxmax(self, axis=0, skipna=True, *args, **kwargs):
if skipna is None:
skipna = True
return super(Series, self).idxmax(axis=axis, skipna=skipna, *args, **kwargs)
def idxmin(self, axis=0, skipna=True, *args, **kwargs):
if skipna is None:
skipna = True
return super(Series, self).idxmin(axis=axis, skipna=skipna, *args, **kwargs)
def interpolate(
self,
method="linear",
axis=0,
limit=None,
inplace=False,
limit_direction: Optional[str] = None,
limit_area=None,
downcast=None,
**kwargs,
):
return self._default_to_pandas(
pandas.Series.interpolate,
method=method,
axis=axis,
limit=limit,
inplace=inplace,
limit_direction=limit_direction,
limit_area=limit_area,
downcast=downcast,
**kwargs,
)
def item(self):
return self[0]
def items(self):
def item_builder(s):
return s.name, s.squeeze()
partition_iterator = PartitionIterator(self.to_frame(), 0, item_builder)
for v in partition_iterator:
yield v
def iteritems(self):
return self.items()
def keys(self):
return self.index
def le(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).le(new_other, level=level, axis=axis)
def lt(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).lt(new_other, level=level, axis=axis)
def map(self, arg, na_action=None):
if not callable(arg) and hasattr(arg, "get"):
mapper = arg
def arg(s):
return mapper.get(s, np.nan)
return self.__constructor__(
query_compiler=self._query_compiler.applymap(
lambda s: arg(s)
if pandas.isnull(s) is not True or na_action is None
else s
)
)
def memory_usage(self, index=True, deep=False):
if index:
result = self._reduce_dimension(
self._query_compiler.memory_usage(index=False, deep=deep)
)
index_value = self.index.memory_usage(deep=deep)
return result + index_value
return super(Series, self).memory_usage(index=index, deep=deep)
def mod(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).mod(
new_other, level=level, fill_value=None, axis=axis
)
def mode(self, dropna=True):
return super(Series, self).mode(numeric_only=False, dropna=dropna)
def mul(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).mul(
new_other, level=level, fill_value=None, axis=axis
)
multiply = rmul = mul
def ne(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).ne(new_other, level=level, axis=axis)
def nlargest(self, n=5, keep="first"):
return self._default_to_pandas(pandas.Series.nlargest, n=n, keep=keep)
def nsmallest(self, n=5, keep="first"):
return Series(query_compiler=self._query_compiler.nsmallest(n=n, keep=keep))
def slice_shift(self, periods=1, axis=0):
if periods == 0:
return self.copy()
if axis == "index" or axis == 0:
if abs(periods) >= len(self.index):
return Series(dtype=self.dtype)
else:
if periods > 0:
new_index = self.index.drop(labels=self.index[:periods])
new_df = self.drop(self.index[-periods:])
else:
new_index = self.index.drop(labels=self.index[periods:])
new_df = self.drop(self.index[:-periods])
new_df.index = new_index
return new_df
else:
raise ValueError(
"No axis named {axis} for object type {type}".format(
axis=axis, type=type(self)
)
)
def unstack(self, level=-1, fill_value=None):
from .dataframe import DataFrame
result = DataFrame(
query_compiler=self._query_compiler.unstack(level, fill_value)
)
return result.droplevel(0, axis=1) if result.columns.nlevels > 1 else result
@property
def plot(
self,
kind="line",
ax=None,
figsize=None,
use_index=True,
title=None,
grid=None,
legend=False,
style=None,
logx=False,
logy=False,
loglog=False,
xticks=None,
yticks=None,
xlim=None,
ylim=None,
rot=None,
fontsize=None,
colormap=None,
table=False,
yerr=None,
xerr=None,
label=None,
secondary_y=False,
**kwds,
):
return self._to_pandas().plot
def pow(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).pow(
new_other, level=level, fill_value=None, axis=axis
)
def prod(
self,
axis=None,
skipna=None,
level=None,
numeric_only=None,
min_count=0,
**kwargs,
):
axis = self._get_axis_number(axis)
new_index = self.columns if axis else self.index
if min_count > len(new_index):
return np.nan
data = self._validate_dtypes_sum_prod_mean(axis, numeric_only, ignore_axis=True)
if level is not None:
return data.__constructor__(
query_compiler=data._query_compiler.prod_min_count(
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
min_count=min_count,
**kwargs,
)
)
if min_count > 1:
return data._reduce_dimension(
data._query_compiler.prod_min_count(
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
min_count=min_count,
**kwargs,
)
)
return data._reduce_dimension(
data._query_compiler.prod(
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
min_count=min_count,
**kwargs,
)
)
product = prod
radd = add
def ravel(self, order="C"):
data = self._query_compiler.to_numpy().flatten(order=order)
if isinstance(self.dtype, pandas.CategoricalDtype):
data = pandas.Categorical(data, dtype=self.dtype)
return data
def reindex(self, index=None, **kwargs):
method = kwargs.pop("method", None)
level = kwargs.pop("level", None)
copy = kwargs.pop("copy", True)
limit = kwargs.pop("limit", None)
tolerance = kwargs.pop("tolerance", None)
fill_value = kwargs.pop("fill_value", None)
if kwargs:
raise TypeError(
"reindex() got an unexpected keyword "
'argument "{0}"'.format(list(kwargs.keys())[0])
)
return super(Series, self).reindex(
index=index,
method=method,
level=level,
copy=copy,