-
Notifications
You must be signed in to change notification settings - Fork 354
/
series.py
3001 lines (2518 loc) · 89.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
#
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed 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.
#
"""
A wrapper class for Spark Column to behave similar to pandas Series.
"""
import re
import inspect
from collections import Iterable
from functools import partial, wraps
from typing import Any, Optional, List, Union, Generic, TypeVar
import numpy as np
import pandas as pd
from pandas.core.accessor import CachedAccessor
from pyspark import sql as spark
from pyspark.sql import functions as F, Column
from pyspark.sql.types import BooleanType, StructType
from pyspark.sql.window import Window
from databricks import koalas as ks # For running doctests and reference resolution in PyCharm.
from databricks.koalas.base import IndexOpsMixin
from databricks.koalas.frame import DataFrame
from databricks.koalas.generic import _Frame, max_display_count
from databricks.koalas.internal import IndexMap, _InternalFrame
from databricks.koalas.missing.series import _MissingPandasLikeSeries
from databricks.koalas.plot import KoalasSeriesPlotMethods
from databricks.koalas.utils import validate_arguments_and_invoke_function, scol_for
from databricks.koalas.datetimes import DatetimeMethods
from databricks.koalas.strings import StringMethods
# This regular expression pattern is complied and defined here to avoid to compile the same
# pattern every time it is used in _repr_ in Series.
# This pattern basically seeks the footer string from Pandas'
REPR_PATTERN = re.compile(r"Length: (?P<length>[0-9]+)")
_flex_doc_SERIES = """
Return {desc} of series and other, element-wise (binary operator `{op_name}`).
Equivalent to ``{equiv}``
Parameters
----------
other : Series or scalar value
Returns
-------
Series
The result of the operation.
See Also
--------
Series.{reverse}
{series_examples}
"""
_add_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [1, 1, 1, np.nan],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 1.0 1.0
b 1.0 NaN
c 1.0 1.0
d NaN NaN
>>> df.a.add(df.b)
a 2.0
b NaN
c 2.0
d NaN
Name: a, dtype: float64
"""
_sub_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [1, 1, 1, np.nan],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 1.0 1.0
b 1.0 NaN
c 1.0 1.0
d NaN NaN
>>> df.a.subtract(df.b)
a 0.0
b NaN
c 0.0
d NaN
Name: a, dtype: float64
"""
_mul_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.multiply(df.b)
a 4.0
b NaN
c 8.0
d NaN
Name: a, dtype: float64
"""
_div_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.divide(df.b)
a 1.0
b NaN
c 2.0
d NaN
Name: a, dtype: float64
"""
_pow_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.pow(df.b)
a 4.0
b NaN
c 16.0
d NaN
Name: a, dtype: float64
"""
_mod_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.mod(df.b)
a 0.0
b NaN
c 0.0
d NaN
Name: a, dtype: float64
"""
_floordiv_example_SERIES = """
Examples
--------
>>> df = ks.DataFrame({'a': [2, 2, 4, np.nan],
... 'b': [2, np.nan, 2, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df
a b
a 2.0 2.0
b 2.0 NaN
c 4.0 2.0
d NaN NaN
>>> df.a.floordiv(df.b)
a 1.0
b NaN
c 2.0
d NaN
Name: a, dtype: float64
"""
T = TypeVar("T")
# Needed to disambiguate Series.str and str type
str_type = str
class Series(_Frame, IndexOpsMixin, Generic[T]):
"""
Koala Series that corresponds to Pandas Series logically. This holds Spark Column
internally.
:ivar _internal: an internal immutable Frame to manage metadata.
:type _internal: _InternalFrame
:ivar _kdf: Parent's Koalas DataFrame
:type _kdf: ks.DataFrame
Parameters
----------
data : array-like, dict, or scalar value, Pandas Series
Contains data stored in Series
If data is a dict, argument order is maintained for Python 3.6
and later.
Note that if `data` is a Pandas Series, other arguments should not be used.
index : array-like or Index (1d)
Values must be hashable and have the same length as `data`.
Non-unique index values are allowed. Will default to
RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index
sequence are used, the index will override the keys found in the
dict.
dtype : numpy.dtype or None
If None, dtype will be inferred
copy : boolean, default False
Copy input data
"""
def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False,
anchor=None):
if isinstance(data, _InternalFrame):
assert dtype is None
assert name is None
assert not copy
assert not fastpath
IndexOpsMixin.__init__(self, data, anchor)
else:
if isinstance(data, pd.Series):
assert index is None
assert dtype is None
assert name is None
assert not copy
assert anchor is None
assert not fastpath
s = data
else:
s = pd.Series(
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath)
kdf = DataFrame(s)
IndexOpsMixin.__init__(self, kdf._internal.copy(scol=kdf._internal.data_scols[0]), kdf)
@property
def _index_map(self) -> List[IndexMap]:
return self._internal.index_map
def _with_new_scol(self, scol: spark.Column) -> 'Series':
"""
Copy Koalas Series with the new Spark Column.
:param scol: the new Spark Column
:return: the copied Series
"""
return Series(self._kdf._internal.copy(scol=scol), anchor=self._kdf)
@property
def dtypes(self):
"""Return the dtype object of the underlying data.
>>> s = ks.Series(list('abc'))
>>> s.dtype == s.dtypes
True
"""
return self.dtype
@property
def spark_type(self):
""" Returns the data type as defined by Spark, as a Spark DataType object."""
return self.schema.fields[-1].dataType
plot = CachedAccessor("plot", KoalasSeriesPlotMethods)
# Arithmetic Operators
def add(self, other):
return (self + other).rename(self.name)
add.__doc__ = _flex_doc_SERIES.format(
desc='Addition',
op_name="+",
equiv="series + other",
reverse='radd',
series_examples=_add_example_SERIES)
def radd(self, other):
return (other + self).rename(self.name)
radd.__doc__ = _flex_doc_SERIES.format(
desc='Addition',
op_name="+",
equiv="other + series",
reverse='add',
series_examples=_add_example_SERIES)
def div(self, other):
return (self / other).rename(self.name)
div.__doc__ = _flex_doc_SERIES.format(
desc='Floating division',
op_name="/",
equiv="series / other",
reverse='rdiv',
series_examples=_div_example_SERIES)
divide = div
def rdiv(self, other):
return (other / self).rename(self.name)
rdiv.__doc__ = _flex_doc_SERIES.format(
desc='Floating division',
op_name="/",
equiv="other / series",
reverse='div',
series_examples=_div_example_SERIES)
def truediv(self, other):
return (self / other).rename(self.name)
truediv.__doc__ = _flex_doc_SERIES.format(
desc='Floating division',
op_name="/",
equiv="series / other",
reverse='rtruediv',
series_examples=_div_example_SERIES)
def rtruediv(self, other):
return (other / self).rename(self.name)
rtruediv.__doc__ = _flex_doc_SERIES.format(
desc='Floating division',
op_name="/",
equiv="other / series",
reverse='truediv',
series_examples=_div_example_SERIES)
def mul(self, other):
return (self * other).rename(self.name)
mul.__doc__ = _flex_doc_SERIES.format(
desc='Multiplication',
op_name="*",
equiv="series * other",
reverse='rmul',
series_examples=_mul_example_SERIES)
multiply = mul
def rmul(self, other):
return (other * self).rename(self.name)
rmul.__doc__ = _flex_doc_SERIES.format(
desc='Multiplication',
op_name="*",
equiv="other * series",
reverse='mul',
series_examples=_mul_example_SERIES)
def sub(self, other):
return (self - other).rename(self.name)
sub.__doc__ = _flex_doc_SERIES.format(
desc='Subtraction',
op_name="-",
equiv="series - other",
reverse='rsub',
series_examples=_sub_example_SERIES)
subtract = sub
def rsub(self, other):
return (other - self).rename(self.name)
rsub.__doc__ = _flex_doc_SERIES.format(
desc='Subtraction',
op_name="-",
equiv="other - series",
reverse='sub',
series_examples=_sub_example_SERIES)
def mod(self, other):
return (self % other).rename(self.name)
mod.__doc__ = _flex_doc_SERIES.format(
desc='Modulo',
op_name='%',
equiv='series % other',
reverse='rmod',
series_examples=_mod_example_SERIES)
def rmod(self, other):
return (other % self).rename(self.name)
rmod.__doc__ = _flex_doc_SERIES.format(
desc='Modulo',
op_name='%',
equiv='other % series',
reverse='mod',
series_examples=_mod_example_SERIES)
def pow(self, other):
return (self ** other).rename(self.name)
pow.__doc__ = _flex_doc_SERIES.format(
desc='Exponential power of series',
op_name='**',
equiv='series ** other',
reverse='rpow',
series_examples=_pow_example_SERIES)
def rpow(self, other):
return (other - self).rename(self.name)
rpow.__doc__ = _flex_doc_SERIES.format(
desc='Exponential power',
op_name='**',
equiv='other ** series',
reverse='pow',
series_examples=_pow_example_SERIES)
def floordiv(self, other):
return (self // other).rename(self.name)
floordiv.__doc__ = _flex_doc_SERIES.format(
desc='Integer division',
op_name='//',
equiv='series // other',
reverse='rfloordiv',
series_examples=_floordiv_example_SERIES)
def rfloordiv(self, other):
return (other - self).rename(self.name)
rfloordiv.__doc__ = _flex_doc_SERIES.format(
desc='Integer division',
op_name='//',
equiv='other // series',
reverse='floordiv',
series_examples=_floordiv_example_SERIES)
# Comparison Operators
def eq(self, other):
"""
Compare if the current value is equal to the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a == 1
a True
b False
c False
d False
Name: (a = 1), dtype: bool
>>> df.b.eq(1)
a True
b None
c True
d None
Name: b, dtype: object
"""
return (self == other).rename(self.name)
equals = eq
def gt(self, other):
"""
Compare if the current value is greater than the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a > 1
a False
b True
c True
d True
Name: (a > 1), dtype: bool
>>> df.b.gt(1)
a False
b None
c False
d None
Name: b, dtype: object
"""
return (self > other).rename(self.name)
def ge(self, other):
"""
Compare if the current value is greater than or equal to the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a >= 2
a False
b True
c True
d True
Name: (a >= 2), dtype: bool
>>> df.b.ge(2)
a False
b None
c False
d None
Name: b, dtype: object
"""
return (self >= other).rename(self.name)
def lt(self, other):
"""
Compare if the current value is less than the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a < 1
a False
b False
c False
d False
Name: (a < 1), dtype: bool
>>> df.b.lt(2)
a True
b None
c True
d None
Name: b, dtype: object
"""
return (self < other).rename(self.name)
def le(self, other):
"""
Compare if the current value is less than or equal to the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a <= 2
a True
b True
c False
d False
Name: (a <= 2), dtype: bool
>>> df.b.le(2)
a True
b None
c True
d None
Name: b, dtype: object
"""
return (self <= other).rename(self.name)
def ne(self, other):
"""
Compare if the current value is not equal to the other.
>>> df = ks.DataFrame({'a': [1, 2, 3, 4],
... 'b': [1, np.nan, 1, np.nan]},
... index=['a', 'b', 'c', 'd'], columns=['a', 'b'])
>>> df.a != 1
a False
b True
c True
d True
Name: (NOT (a = 1)), dtype: bool
>>> df.b.ne(1)
a False
b None
c False
d None
Name: b, dtype: object
"""
return (self != other).rename(self.name)
# TODO: arg should support Series
# TODO: NaN and None
def map(self, arg):
"""
Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value,
that may be derived from a function, a ``dict``.
.. note:: make sure the size of the dictionary is not huge because it could
downgrade the performance or throw OutOfMemoryError due to a huge
expression within Spark. Consider the input as a functions as an
alternative instead in this case.
Parameters
----------
arg : function or dict
Mapping correspondence.
Returns
-------
Series
Same index as caller.
See Also
--------
Series.apply : For applying more complex functions on a Series.
DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
Notes
-----
When ``arg`` is a dictionary, values in Series that are not in the
dictionary (as keys) are converted to ``None``. However, if the
dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
provides a method for default values), then this default is used
rather than ``None``.
Examples
--------
>>> s = ks.Series(['cat', 'dog', None, 'rabbit'])
>>> s
0 cat
1 dog
2 None
3 rabbit
Name: 0, dtype: object
``map`` accepts a ``dict``. Values that are not found
in the ``dict`` are converted to ``None``, unless the dict has a default
value (e.g. ``defaultdict``):
>>> s.map({'cat': 'kitten', 'dog': 'puppy'})
0 kitten
1 puppy
2 None
3 None
Name: 0, dtype: object
It also accepts a function:
>>> def format(x) -> str:
... return 'I am a {}'.format(x)
>>> s.map(format)
0 I am a cat
1 I am a dog
2 I am a None
3 I am a rabbit
Name: 0, dtype: object
"""
if isinstance(arg, dict):
is_start = True
# In case dictionary is empty.
current = F.when(F.lit(False), F.lit(None).cast(self.spark_type))
for to_replace, value in arg.items():
if is_start:
current = F.when(self._scol == F.lit(to_replace), value)
is_start = False
else:
current = current.when(self._scol == F.lit(to_replace), value)
if hasattr(arg, "__missing__"):
tmp_val = arg[np._NoValue]
del arg[np._NoValue] # Remove in case it's set in defaultdict.
current = current.otherwise(F.lit(tmp_val))
else:
current = current.otherwise(F.lit(None).cast(self.spark_type))
return Series(self._kdf._internal.copy(scol=current),
anchor=self._kdf).rename(self.name)
else:
return self.apply(arg)
def astype(self, dtype) -> 'Series':
"""
Cast a Koalas object to a specified dtype ``dtype``.
Parameters
----------
dtype : data type
Use a numpy.dtype or Python type to cast entire pandas object to
the same type.
Returns
-------
casted : same type as caller
See Also
--------
to_datetime : Convert argument to datetime.
Examples
--------
>>> ser = ks.Series([1, 2], dtype='int32')
>>> ser
0 1
1 2
Name: 0, dtype: int32
>>> ser.astype('int64')
0 1
1 2
Name: 0, dtype: int64
"""
from databricks.koalas.typedef import as_spark_type
spark_type = as_spark_type(dtype)
if not spark_type:
raise ValueError("Type {} not understood".format(dtype))
return Series(self._kdf._internal.copy(scol=self._scol.cast(spark_type)), anchor=self._kdf)
def getField(self, name):
if not isinstance(self.schema, StructType):
raise AttributeError("Not a struct: {}".format(self.schema))
else:
fnames = self.schema.fieldNames()
if name not in fnames:
raise AttributeError(
"Field {} not found, possible values are {}".format(name, ", ".join(fnames)))
return Series(self._kdf._internal.copy(scol=self._scol.getField(name)),
anchor=self._kdf)
def alias(self, name):
"""An alias for :meth:`Series.rename`."""
return self.rename(name)
@property
def schema(self) -> StructType:
"""Return the underlying Spark DataFrame's schema."""
return self.to_dataframe()._sdf.schema
@property
def shape(self):
"""Return a tuple of the shape of the underlying data."""
return len(self),
@property
def ndim(self):
"""Returns number of dimensions of the Series."""
return 1
@property
def name(self) -> str:
"""Return name of the Series."""
return self._internal.data_columns[0]
@name.setter
def name(self, name):
self.rename(name, inplace=True)
# TODO: Functionality and documentation should be matched. Currently, changing index labels
# taking dictionary and function to change index are not supported.
def rename(self, index=None, **kwargs):
"""
Alter Series name.
Parameters
----------
index : scalar
Scalar will alter the ``Series.name`` attribute.
inplace : bool, default False
Whether to return a new Series. If True then value of copy is
ignored.
Returns
-------
Series
Series with name altered.
Examples
--------
>>> s = ks.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
Name: 0, dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
"""
if index is None:
scol = self._scol
else:
scol = self._scol.alias(index)
if kwargs.get('inplace', False):
self._internal = self._internal.copy(scol=scol)
return self
else:
return Series(self._kdf._internal.copy(scol=scol), anchor=self._kdf)
@property
def index(self):
"""The index (axis labels) Column of the Series.
Currently not supported when the DataFrame has no index.
See Also
--------
Index
"""
return self._kdf.index
@property
def is_unique(self):
"""
Return boolean if values in the object are unique
Returns
-------
is_unique : boolean
>>> ks.Series([1, 2, 3]).is_unique
True
>>> ks.Series([1, 2, 2]).is_unique
False
>>> ks.Series([1, 2, 3, None]).is_unique
True
"""
sdf = self._kdf._sdf.select(self._scol)
col = self._scol
# Here we check:
# 1. the distinct count without nulls and count without nulls for non-null values
# 2. count null values and see if null is a distinct value.
#
# This workaround is in order to calculate the distinct count including nulls in
# single pass. Note that COUNT(DISTINCT expr) in Spark is designed to ignore nulls.
return sdf.select(
(F.count(col) == F.countDistinct(col)) &
(F.count(F.when(col.isNull(), 1).otherwise(None)) <= 1)
).collect()[0][0]
def reset_index(self, level=None, drop=False, name=None, inplace=False):
"""
Generate a new DataFrame or Series with the index reset.
This is useful when the index needs to be treated as a column,
or when the index is meaningless and needs to be reset
to the default before another operation.
Parameters
----------
level : int, str, tuple, or list, default optional
For a Series with a MultiIndex, only remove the specified levels from the index.
Removes all levels by default.
drop : bool, default False
Just reset the index, without inserting it as a column in the new DataFrame.
name : object, optional
The name to use for the column containing the original Series values.
Uses self.name by default. This argument is ignored when drop is True.
inplace : bool, default False
Modify the Series in place (do not create a new object).
Returns
-------
Series or DataFrame
When `drop` is False (the default), a DataFrame is returned.
The newly created columns will come first in the DataFrame,
followed by the original Series values.
When `drop` is True, a `Series` is returned.
In either case, if ``inplace=True``, no value is returned.
Examples
--------
>>> s = ks.Series([1, 2, 3, 4], name='foo',
... index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))
Generate a DataFrame with default index.
>>> s.reset_index()
idx foo
0 a 1
1 b 2
2 c 3
3 d 4
To specify the name of the new column use `name`.
>>> s.reset_index(name='values')
idx values
0 a 1
1 b 2
2 c 3
3 d 4
To generate a new Series with the default set `drop` to True.
>>> s.reset_index(drop=True)
0 1
1 2
2 3
3 4
Name: foo, dtype: int64
To update the Series in place, without generating a new one
set `inplace` to True. Note that it also requires ``drop=True``.
>>> s.reset_index(inplace=True, drop=True)
>>> s
0 1
1 2
2 3
3 4
Name: foo, dtype: int64
"""
if inplace and not drop:
raise TypeError('Cannot reset_index inplace on a Series to create a DataFrame')
if name is not None:
kdf = self.rename(name).to_dataframe()
else:
kdf = self.to_dataframe()
kdf = kdf.reset_index(level=level, drop=drop)
if drop:
kseries = _col(kdf)
if inplace:
self._internal = kseries._internal
self._kdf = kseries._kdf
else:
return kseries
else:
return kdf
def to_frame(self, name=None) -> spark.DataFrame:
"""
Convert Series to DataFrame.
Parameters
----------
name : object, default None
The passed name should substitute for the series name (if it has
one).
Returns
-------
DataFrame
DataFrame representation of Series.
Examples
--------
>>> s = ks.Series(["a", "b", "c"])
>>> s.to_frame()
0
0 a
1 b
2 c
>>> s = ks.Series(["a", "b", "c"], name="vals")
>>> s.to_frame()
vals
0 a
1 b
2 c