/
series.py
1303 lines (1104 loc) · 41.1 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas
from pandas.compat import string_types
from pandas.core.common import is_bool_indexer
from pandas.core.dtypes.common import is_dict_like, is_list_like, is_scalar
import sys
import warnings
from .base import BasePandasDataset
from .iterator import PartitionIterator
from .utils import _inherit_docstrings
from .utils import from_pandas, to_pandas
@_inherit_docstrings(pandas.Series, excluded=[pandas.Series, pandas.Series.__init__])
class Series(BasePandasDataset):
def __init__(
self,
data=None,
index=None,
dtype=None,
name=None,
copy=False,
fastpath=False,
query_compiler=None,
):
"""Constructor for a Series object.
Args:
series_oids ([ObjectID]): The list of remote Series objects.
"""
if query_compiler is None:
warnings.warn(
"Distributing {} object. This may take some time.".format(type(data))
)
if name is None:
name = "__reduced__"
query_compiler = from_pandas(
pandas.DataFrame(
pandas.Series(
data=data,
index=index,
dtype=dtype,
name=name,
copy=copy,
fastpath=fastpath,
)
)
)._query_compiler
if len(query_compiler.columns) != 1 or (
len(query_compiler.index) == 1 and query_compiler.index[0] == "__reduced__"
):
query_compiler = query_compiler.transpose()
self._query_compiler = query_compiler
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
def _reduce_dimension(self, query_compiler):
return query_compiler.to_pandas().squeeze()
def _validate_dtypes_sum_prod_mean(self, axis, numeric_only, ignore_axis=False):
return self
def _validate_dtypes_min_max(self, axis, numeric_only):
return self
def _validate_dtypes(self, numeric_only=False):
pass
def _create_or_update_from_compiler(self, new_query_compiler, inplace=False):
"""Returns or updates a DataFrame given new query_compiler"""
assert (
isinstance(new_query_compiler, type(self._query_compiler))
or type(new_query_compiler) in self._query_compiler.__class__.__bases__
), "Invalid Query Compiler object: {}".format(type(new_query_compiler))
if not inplace and (
len(new_query_compiler.columns) == 1 or len(new_query_compiler.index) == 1
):
return Series(query_compiler=new_query_compiler)
elif not inplace:
# This can happen with things like `reset_index` where we can add columns.
from .dataframe import DataFrame
return DataFrame(query_compiler=new_query_compiler)
else:
self._update_inplace(new_query_compiler=new_query_compiler)
def _prepare_inter_op(self, other):
if isinstance(other, Series):
new_self = self.copy()
new_self.name = "__reduced__"
new_other = other.copy()
new_other.name = "__reduced__"
else:
new_self = self
new_other = other
return new_self, new_other
def __add__(self, right):
return self.add(right)
def __and__(self, other):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).__and__(new_other)
def __array_prepare__(self, result, context=None): # pragma: no cover
return self._default_to_pandas(
pandas.Series.__array_prepare__, result, context=context
)
@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 __divmod__(self, right):
return self.divmod(right)
def __float__(self):
return float(self.squeeze())
def __floordiv__(self, right):
return self.floordiv(right)
def _getitem(self, key):
if isinstance(key, Series) and key.dtype == np.bool:
# This ends up being significantly faster than looping through and getting
# each item individually.
key = key._to_pandas()
if is_bool_indexer(key):
return self.__constructor__(
query_compiler=self._query_compiler.getitem_row_array(
pandas.RangeIndex(len(self.index))[key]
)
)
# TODO: More efficiently handle `tuple` case for `Series.__getitem__`
if isinstance(key, tuple):
return self._default_to_pandas(pandas.Series.__getitem__, key)
else:
if not is_list_like(key):
reduce_dimension = True
key = [key]
else:
reduce_dimension = False
# The check for whether or not `key` is in `keys()` will throw a TypeError
# if the object is not hashable. When that happens, we just use the `iloc`.
try:
if all(k in self.keys() for k in key):
result = self._query_compiler.getitem_row_array(
self.index.get_indexer_for(key)
)
else:
result = self._query_compiler.getitem_row_array(key)
except TypeError:
result = self._query_compiler.getitem_row_array(key)
if reduce_dimension:
return self._reduce_dimension(result)
return self.__constructor__(query_compiler=result)
def __int__(self):
return int(self.squeeze())
def __iter__(self):
return self._to_pandas().__iter__()
def __mod__(self, right):
return self.mod(right)
def __mul__(self, right):
return self.mul(right)
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 __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):
temp_df = temp_df.iloc[:, 0]
temp_str = repr(temp_df)
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(temp_str.rsplit("dtype: ", 1)[-1])
if len(self) == 0:
return "Series([], {}{}".format(name_str, dtype_str)
return temp_str.rsplit("\nName:", 1)[0] + "\n{}{}{}".format(
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 __truediv__(self, right):
return self.truediv(right)
__iadd__ = __add__
__imul__ = __add__
__ipow__ = __pow__
__isub__ = __sub__
__itruediv__ = __truediv__
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):
"""Add a prefix to each of the column names.
Returns:
A new Series containing the new column names.
"""
return Series(query_compiler=self._query_compiler.add_prefix(prefix, axis=0))
def add_suffix(self, suffix):
"""Add a suffix to each of the column names.
Returns:
A new DataFrame containing the new column names.
"""
return Series(query_compiler=self._query_compiler.add_suffix(suffix, axis=0))
def append(self, to_append, ignore_index=False, verify_integrity=False):
"""Append another DataFrame/list/Series to this one.
Args:
to_append: The object to append to this.
ignore_index: Ignore the index on appending.
verify_integrity: Verify the integrity of the index on completion.
Returns:
A new DataFrame containing the concatenated values.
"""
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 `self.__name__` for the return
# type.
# Because a `Series` cannot be empty in pandas, 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:
return_type = self.__name__
if (
isinstance(func, string_types)
or is_list_like(func)
or return_type not in ["DataFrame", "Series"]
):
query_compiler = super(Series, self).apply(func, *args, **kwds)
# Sometimes we can return a scalar here
if not isinstance(query_compiler, type(self._query_compiler)):
return query_compiler
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)
query_compiler = self.map(f)._query_compiler
if return_type not in ["DataFrame", "Series"]:
return query_compiler.to_pandas().squeeze()
else:
result = getattr(sys.modules[self.__module__], return_type)(
query_compiler=query_compiler
)
if result.name == self.index[0]:
result.name = None
return result
def argmax(self, axis=0, skipna=True, *args, **kwargs):
# Series and DataFrame have a different behavior for `skipna`
if skipna is None:
skipna = True
return self.idxmax(axis=axis, skipna=skipna, *args, **kwargs)
def argmin(self, axis=0, skipna=True, *args, **kwargs):
# Series and DataFrame have a different behavior for `skipna`
if skipna is None:
skipna = True
return self.idxmin(axis=axis, skipna=skipna, *args, **kwargs)
def argsort(self, axis=0, kind="quicksort", order=None):
return self._default_to_pandas(
pandas.Series.argsort, axis=axis, kind=kind, order=order
)
def array(self):
return self._default_to_pandas(pandas.Series.array)
def autocorr(self, lag=1):
return self._default_to_pandas(pandas.Series.autocorr, lag=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, func, fill_value=fill_value)
def compound(self, axis=None, skipna=None, level=None):
return self._default_to_pandas(
pandas.Series.compound, axis=axis, skipna=skipna, level=level
)
def compress(self, condition, *args, **kwargs):
return self._default_to_pandas(
pandas.Series.compress, condition, *args, **kwargs
)
def convert_objects(
self,
convert_dates=True,
convert_numeric=False,
convert_timedeltas=True,
copy=True,
):
return self._default_to_pandas(
pandas.Series.convert_objects,
convert_dates=convert_dates,
convert_numeric=convert_numeric,
convert_timedeltas=convert_timedeltas,
copy=copy,
)
def corr(self, other, method="pearson", min_periods=None):
if isinstance(other, BasePandasDataset):
other = other._to_pandas()
return self._default_to_pandas(
pandas.Series.corr, other, 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):
if isinstance(other, BasePandasDataset):
other = other._to_pandas()
return self._default_to_pandas(
pandas.Series.cov, other, min_periods=min_periods
)
def describe(self, percentiles=None, include=None, exclude=None):
# Pandas ignores the `include` and `exclude` for Series for some reason.
return super(Series, self).describe(percentiles=percentiles)
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 drop_duplicates(self, keep="first", inplace=False):
return super(Series, self).drop_duplicates(keep=keep, inplace=inplace)
def dropna(self, axis=0, inplace=False, **kwargs):
kwargs.pop("how", None)
if kwargs:
raise TypeError(
"dropna() got an unexpected keyword "
'argument "{0}"'.format(list(kwargs.keys())[0])
)
return super(Series, self).dropna(axis=axis, inplace=inplace)
def duplicated(self, keep="first"):
return super(Series, self).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 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 from_array(
self, arr, index=None, name=None, dtype=None, copy=False, fastpath=False
):
raise NotImplementedError("Not Yet implemented.")
def from_csv(
self,
path,
sep=",",
parse_dates=True,
header=None,
index_col=0,
encoding=None,
infer_datetime_format=False,
):
return super(Series, self).from_csv(
path,
sep=sep,
parse_dates=parse_dates,
header=header,
index_col=index_col,
encoding=encoding,
infer_datetime_format=infer_datetime_format,
)
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 get_value(self, label, takeable=False):
return self._default_to_pandas(
pandas.Series.get_value, label, takeable=takeable
)
def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=True,
group_keys=True,
squeeze=False,
observed=False,
**kwargs
):
return self._default_to_pandas(
pandas.Series.groupby,
by=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze,
observed=observed,
**kwargs
)
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 head(self, n=5):
if n == 0:
return Series(dtype=self.dtype)
return super(Series, self).head(n)
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="forward",
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):
index_iter = iter(self.index)
def item_builder(df):
s = df.iloc[:, 0]
s.index = [next(index_iter)]
s.name = self.name
return s.items()
partition_iterator = PartitionIterator(self._query_compiler, 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):
return self.__constructor__(
query_compiler=self._query_compiler._map_partitions(
lambda df: pandas.DataFrame(df.iloc[:, 0].map(arg, na_action=na_action))
)
)
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 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 nonzero(self):
return self.to_numpy().nonzero()
def nsmallest(self, n=5, keep="first"):
return self._default_to_pandas(pandas.Series.nsmallest, n=n, keep=keep)
@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
return super(Series, self).prod(
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
min_count=min_count,
**kwargs
)
product = prod
def ptp(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return self._default_to_pandas(
pandas.Series.ptp,
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
**kwargs
)
def put(self, *args, **kwargs):
return self._default_to_pandas(pandas.Series.put, *args, **kwargs)
radd = add
def ravel(self, order="C"):
return self._default_to_pandas(pandas.Series.ravel, order=order)
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,
limit=limit,
tolerance=tolerance,
fill_value=fill_value,
)
def reindex_axis(self, labels, axis=0, **kwargs):
if axis != 0:
raise ValueError("cannot reindex series on non-zero axis!")
return self.reindex(index=labels, **kwargs)
def rename(self, index=None, **kwargs):
non_mapping = is_scalar(index) or (
is_list_like(index) and not is_dict_like(index)
)
if non_mapping:
if kwargs.get("inplace", False):
self.name = index
else:
self_cp = self.copy()
self_cp.name = index
return self_cp
else:
from .dataframe import DataFrame
result = DataFrame(self.copy()).rename(index=index, **kwargs).squeeze()
result.name = self.name
return result
def reorder_levels(self, order):
return self._default_to_pandas(pandas.Series.reorder_levels, order)
def repeat(self, repeats, axis=None):
return self._default_to_pandas(pandas.Series.repeat, repeats, axis=axis)
def reset_index(self, level=None, drop=False, name=None, inplace=False):
if drop and level is None:
new_idx = pandas.RangeIndex(len(self.index))
if inplace:
self.index = new_idx
self.name = name or self.name
else:
result = self.copy()
result.index = new_idx
result.name = name or self.name
return result
elif not drop and inplace:
raise TypeError(
"Cannot reset_index inplace on a Series to create a DataFrame"
)
else:
obj = self.copy()
if name is not None:
obj.name = name
from .dataframe import DataFrame
return DataFrame(self.copy()).reset_index(
level=level, drop=drop, inplace=inplace
)
def rdivmod(self, other, level=None, fill_value=None, axis=0):
return self._default_to_pandas(
pandas.Series.rdivmod, other, level=level, fill_value=fill_value, axis=axis
)
def rfloordiv(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).rfloordiv(
new_other, level=level, fill_value=None, axis=axis
)
def rmod(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).rmod(
new_other, level=level, fill_value=None, axis=axis
)
def rpow(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).rpow(
new_other, level=level, fill_value=None, axis=axis
)
def rsub(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).rsub(
new_other, level=level, fill_value=None, axis=axis
)
def rtruediv(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).rtruediv(
new_other, level=level, fill_value=None, axis=axis
)
rdiv = rtruediv
def searchsorted(self, value, side="left", sorter=None):
return self._default_to_pandas(
pandas.Series.searchsorted, value, side=side, sorter=sorter
)
def set_value(self, label, value, takeable=False):
return self._default_to_pandas("set_value", label, value, takeable=takeable)
def sort_values(
self,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
):
from .dataframe import DataFrame
# When we convert to a DataFrame, the name is automatically converted to 0 if it
# is None, so we do this to avoid a KeyError.
by = self.name if self.name is not None else 0
result = (
DataFrame(self.copy())
.sort_values(
by=by,
ascending=ascending,
inplace=False,
kind=kind,
na_position=na_position,
)
.squeeze(axis=1)
)
result.name = self.name
return self._create_or_update_from_compiler(
result._query_compiler, inplace=inplace
)
def sparse(self, data=None):
return self._default_to_pandas(pandas.Series.sparse, data=data)
def squeeze(self, axis=None):
if axis is not None:
# Validate `axis`
pandas.Series._get_axis_number(axis)
if len(self.index) == 1:
return self._reduce_dimension(self._query_compiler)
else:
return self.copy()
def sub(self, other, level=None, fill_value=None, axis=0):
new_self, new_other = self._prepare_inter_op(other)
return super(Series, new_self).sub(
new_other, level=level, fill_value=None, axis=axis
)
subtract = sub
def sum(
self,
axis=None,
skipna=None,
level=None,