-
Notifications
You must be signed in to change notification settings - Fork 28k
/
groupby.py
4423 lines (3776 loc) · 147 KB
/
groupby.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 the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF 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.
#
"""
A wrapper for GroupedData to behave like pandas GroupBy.
"""
from abc import ABCMeta, abstractmethod
import inspect
from collections import defaultdict, namedtuple
from distutils.version import LooseVersion
from functools import partial
from itertools import product
from typing import (
Any,
Callable,
Dict,
Generic,
Iterator,
Mapping,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
cast,
TYPE_CHECKING,
)
import warnings
import pandas as pd
from pandas.api.types import is_number, is_hashable, is_list_like # type: ignore[attr-defined]
if LooseVersion(pd.__version__) >= LooseVersion("1.3.0"):
from pandas.core.common import _builtin_table # type: ignore[attr-defined]
else:
from pandas.core.base import SelectionMixin
_builtin_table = SelectionMixin._builtin_table # type: ignore[attr-defined]
from pyspark.sql import Column, DataFrame as SparkDataFrame, Window, functions as F
from pyspark.sql.types import (
BooleanType,
DataType,
DoubleType,
NumericType,
StructField,
StructType,
StringType,
)
from pyspark import pandas as ps # For running doctests and reference resolution in PyCharm.
from pyspark.pandas._typing import Axis, FrameLike, Label, Name
from pyspark.pandas.typedef import infer_return_type, DataFrameType, ScalarType, SeriesType
from pyspark.pandas.frame import DataFrame
from pyspark.pandas.internal import (
InternalField,
InternalFrame,
HIDDEN_COLUMNS,
NATURAL_ORDER_COLUMN_NAME,
SPARK_INDEX_NAME_FORMAT,
SPARK_DEFAULT_SERIES_NAME,
SPARK_INDEX_NAME_PATTERN,
)
from pyspark.pandas.missing.groupby import (
MissingPandasLikeDataFrameGroupBy,
MissingPandasLikeSeriesGroupBy,
)
from pyspark.pandas.series import Series, first_series
from pyspark.pandas.spark import functions as SF
from pyspark.pandas.config import get_option
from pyspark.pandas.utils import (
align_diff_frames,
is_name_like_tuple,
is_name_like_value,
name_like_string,
same_anchor,
scol_for,
verify_temp_column_name,
log_advice,
)
from pyspark.pandas.spark.utils import as_nullable_spark_type, force_decimal_precision_scale
from pyspark.pandas.exceptions import DataError
if TYPE_CHECKING:
from pyspark.pandas.window import RollingGroupby, ExpandingGroupby, ExponentialMovingGroupby
# to keep it the same as pandas
NamedAgg = namedtuple("NamedAgg", ["column", "aggfunc"])
class GroupBy(Generic[FrameLike], metaclass=ABCMeta):
"""
:ivar _psdf: The parent dataframe that is used to perform the groupby
:type _psdf: DataFrame
:ivar _groupkeys: The list of keys that will be used to perform the grouping
:type _groupkeys: List[Series]
"""
def __init__(
self,
psdf: DataFrame,
groupkeys: List[Series],
as_index: bool,
dropna: bool,
column_labels_to_exclude: Set[Label],
agg_columns_selected: bool,
agg_columns: List[Series],
):
self._psdf = psdf
self._groupkeys = groupkeys
self._as_index = as_index
self._dropna = dropna
self._column_labels_to_exclude = column_labels_to_exclude
self._agg_columns_selected = agg_columns_selected
self._agg_columns = agg_columns
@property
def _groupkeys_scols(self) -> List[Column]:
return [s.spark.column for s in self._groupkeys]
@property
def _agg_columns_scols(self) -> List[Column]:
return [s.spark.column for s in self._agg_columns]
@abstractmethod
def _apply_series_op(
self,
op: Callable[["SeriesGroupBy"], Series],
should_resolve: bool = False,
numeric_only: bool = False,
) -> FrameLike:
pass
@abstractmethod
def _handle_output(self, psdf: DataFrame) -> FrameLike:
pass
# TODO: Series support is not implemented yet.
# TODO: not all arguments are implemented comparing to pandas' for now.
def aggregate(
self,
func_or_funcs: Optional[Union[str, List[str], Dict[Name, Union[str, List[str]]]]] = None,
*args: Any,
**kwargs: Any,
) -> DataFrame:
"""Aggregate using one or more operations over the specified axis.
Parameters
----------
func_or_funcs : dict, str or list
a dict mapping from column name (string) to
aggregate functions (string or list of strings).
Returns
-------
Series or DataFrame
The return can be:
* Series : when DataFrame.agg is called with a single function
* DataFrame : when DataFrame.agg is called with several functions
Return Series or DataFrame.
Notes
-----
`agg` is an alias for `aggregate`. Use the alias.
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({'A': [1, 1, 2, 2],
... 'B': [1, 2, 3, 4],
... 'C': [0.362, 0.227, 1.267, -0.562]},
... columns=['A', 'B', 'C'])
>>> df
A B C
0 1 1 0.362
1 1 2 0.227
2 2 3 1.267
3 2 4 -0.562
Different aggregations per column
>>> aggregated = df.groupby('A').agg({'B': 'min', 'C': 'sum'})
>>> aggregated[['B', 'C']].sort_index() # doctest: +NORMALIZE_WHITESPACE
B C
A
1 1 0.589
2 3 0.705
>>> aggregated = df.groupby('A').agg({'B': ['min', 'max']})
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
B
min max
A
1 1 2
2 3 4
>>> aggregated = df.groupby('A').agg('min')
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
B C
A
1 1 0.227
2 3 -0.562
>>> aggregated = df.groupby('A').agg(['min', 'max'])
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
B C
min max min max
A
1 1 2 0.227 0.362
2 3 4 -0.562 1.267
To control the output names with different aggregations per column, pandas-on-Spark
also supports 'named aggregation' or nested renaming in .agg. It can also be
used when applying multiple aggregation functions to specific columns.
>>> aggregated = df.groupby('A').agg(b_max=ps.NamedAgg(column='B', aggfunc='max'))
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
b_max
A
1 2
2 4
>>> aggregated = df.groupby('A').agg(b_max=('B', 'max'), b_min=('B', 'min'))
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
b_max b_min
A
1 2 1
2 4 3
>>> aggregated = df.groupby('A').agg(b_max=('B', 'max'), c_min=('C', 'min'))
>>> aggregated.sort_index() # doctest: +NORMALIZE_WHITESPACE
b_max c_min
A
1 2 0.227
2 4 -0.562
"""
# I think current implementation of func and arguments in pandas-on-Spark for aggregate
# is different than pandas, later once arguments are added, this could be removed.
if func_or_funcs is None and kwargs is None:
raise ValueError("No aggregation argument or function specified.")
relabeling = func_or_funcs is None and is_multi_agg_with_relabel(**kwargs)
if relabeling:
(
func_or_funcs,
columns,
order,
) = normalize_keyword_aggregation( # type: ignore[assignment]
kwargs
)
if not isinstance(func_or_funcs, (str, list)):
if not isinstance(func_or_funcs, dict) or not all(
is_name_like_value(key)
and (
isinstance(value, str)
or isinstance(value, list)
and all(isinstance(v, str) for v in value)
)
for key, value in func_or_funcs.items()
):
raise ValueError(
"aggs must be a dict mapping from column name "
"to aggregate functions (string or list of strings)."
)
else:
agg_cols = [col.name for col in self._agg_columns]
func_or_funcs = {col: func_or_funcs for col in agg_cols}
psdf: DataFrame = DataFrame(
GroupBy._spark_groupby(self._psdf, func_or_funcs, self._groupkeys)
)
if self._dropna:
psdf = DataFrame(
psdf._internal.with_new_sdf(
psdf._internal.spark_frame.dropna(
subset=psdf._internal.index_spark_column_names
)
)
)
if not self._as_index:
should_drop_index = set(
i for i, gkey in enumerate(self._groupkeys) if gkey._psdf is not self._psdf
)
if len(should_drop_index) > 0:
psdf = psdf.reset_index(level=should_drop_index, drop=True)
if len(should_drop_index) < len(self._groupkeys):
psdf = psdf.reset_index()
if relabeling:
psdf = psdf[order]
psdf.columns = columns # type: ignore[assignment]
return psdf
agg = aggregate
@staticmethod
def _spark_groupby(
psdf: DataFrame,
func: Mapping[Name, Union[str, List[str]]],
groupkeys: Sequence[Series] = (),
) -> InternalFrame:
groupkey_names = [SPARK_INDEX_NAME_FORMAT(i) for i in range(len(groupkeys))]
groupkey_scols = [s.spark.column.alias(name) for s, name in zip(groupkeys, groupkey_names)]
multi_aggs = any(isinstance(v, list) for v in func.values())
reordered = []
data_columns = []
column_labels = []
for key, value in func.items():
label = key if is_name_like_tuple(key) else (key,)
if len(label) != psdf._internal.column_labels_level:
raise TypeError("The length of the key must be the same as the column label level.")
for aggfunc in [value] if isinstance(value, str) else value:
column_label = tuple(list(label) + [aggfunc]) if multi_aggs else label
column_labels.append(column_label)
data_col = name_like_string(column_label)
data_columns.append(data_col)
col_name = psdf._internal.spark_column_name_for(label)
if aggfunc == "nunique":
reordered.append(
F.expr("count(DISTINCT `{0}`) as `{1}`".format(col_name, data_col))
)
# Implement "quartiles" aggregate function for ``describe``.
elif aggfunc == "quartiles":
reordered.append(
F.expr(
"percentile_approx(`{0}`, array(0.25, 0.5, 0.75)) as `{1}`".format(
col_name, data_col
)
)
)
else:
reordered.append(
F.expr("{1}(`{0}`) as `{2}`".format(col_name, aggfunc, data_col))
)
sdf = psdf._internal.spark_frame.select(groupkey_scols + psdf._internal.data_spark_columns)
sdf = sdf.groupby(*groupkey_names).agg(*reordered)
return InternalFrame(
spark_frame=sdf,
index_spark_columns=[scol_for(sdf, col) for col in groupkey_names],
index_names=[psser._column_label for psser in groupkeys],
index_fields=[
psser._internal.data_fields[0].copy(name=name)
for psser, name in zip(groupkeys, groupkey_names)
],
column_labels=column_labels,
data_spark_columns=[scol_for(sdf, col) for col in data_columns],
)
def count(self) -> FrameLike:
"""
Compute count of group, excluding missing values.
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2],
... 'B': [np.nan, 2, 3, 4, 5],
... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])
>>> df.groupby('A').count().sort_index() # doctest: +NORMALIZE_WHITESPACE
B C
A
1 2 3
2 2 2
"""
return self._reduce_for_stat_function(F.count)
def first(self, numeric_only: Optional[bool] = False, min_count: int = -1) -> FrameLike:
"""
Compute first of group values.
.. versionadded:: 3.3.0
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
.. versionadded:: 3.4.0
min_count : int, default -1
The required number of valid values to perform the operation. If fewer
than ``min_count`` non-NA values are present the result will be NA.
.. versionadded:: 3.4.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 3, 4, 4], "D": ["a", "b", "a", "a"]})
>>> df
A B C D
0 1 True 3 a
1 2 False 3 b
2 1 False 4 a
3 2 True 4 a
>>> df.groupby("A").first().sort_index()
B C D
A
1 True 3 a
2 False 3 b
Include only float, int, boolean columns when set numeric_only True.
>>> df.groupby("A").first(numeric_only=True).sort_index()
B C
A
1 True 3
2 False 3
>>> df.groupby("D").first().sort_index()
A B C
D
a 1 True 3
b 2 False 3
>>> df.groupby("D").first(min_count=3).sort_index()
A B C
D
a 1.0 True 3.0
b NaN None NaN
"""
if not isinstance(min_count, int):
raise TypeError("min_count must be integer")
return self._reduce_for_stat_function(
lambda col: F.first(col, ignorenulls=True),
accepted_spark_types=(NumericType, BooleanType) if numeric_only else None,
min_count=min_count,
)
def last(self, numeric_only: Optional[bool] = False, min_count: int = -1) -> FrameLike:
"""
Compute last of group values.
.. versionadded:: 3.3.0
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
.. versionadded:: 3.4.0
min_count : int, default -1
The required number of valid values to perform the operation. If fewer
than ``min_count`` non-NA values are present the result will be NA.
.. versionadded:: 3.4.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 3, 4, 4], "D": ["a", "a", "b", "a"]})
>>> df
A B C D
0 1 True 3 a
1 2 False 3 a
2 1 False 4 b
3 2 True 4 a
>>> df.groupby("A").last().sort_index()
B C D
A
1 False 4 b
2 True 4 a
Include only float, int, boolean columns when set numeric_only True.
>>> df.groupby("A").last(numeric_only=True).sort_index()
B C
A
1 False 4
2 True 4
>>> df.groupby("D").last().sort_index()
A B C
D
a 2 True 4
b 1 False 4
>>> df.groupby("D").last(min_count=3).sort_index()
A B C
D
a 2.0 True 4.0
b NaN None NaN
"""
if not isinstance(min_count, int):
raise TypeError("min_count must be integer")
return self._reduce_for_stat_function(
lambda col: F.last(col, ignorenulls=True),
accepted_spark_types=(NumericType, BooleanType) if numeric_only else None,
min_count=min_count,
)
def max(self, numeric_only: Optional[bool] = False, min_count: int = -1) -> FrameLike:
"""
Compute max of group values.
.. versionadded:: 3.3.0
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
.. versionadded:: 3.4.0
min_count : bool, default -1
The required number of valid values to perform the operation. If fewer
than min_count non-NA values are present the result will be NA.
.. versionadded:: 3.4.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "a", "b", "a"]})
>>> df.groupby("A").max().sort_index()
B C D
A
1 True 3 b
2 True 4 a
Include only float, int, boolean columns when set numeric_only True.
>>> df.groupby("A").max(numeric_only=True).sort_index()
B C
A
1 True 3
2 True 4
>>> df.groupby("D").max().sort_index()
A B C
D
a 2 True 4
b 1 False 3
>>> df.groupby("D").max(min_count=3).sort_index()
A B C
D
a 2.0 True 4.0
b NaN None NaN
"""
if not isinstance(min_count, int):
raise TypeError("min_count must be integer")
return self._reduce_for_stat_function(
F.max,
accepted_spark_types=(NumericType, BooleanType) if numeric_only else None,
min_count=min_count,
)
def mean(self, numeric_only: Optional[bool] = True) -> FrameLike:
"""
Compute mean of groups, excluding missing values.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
.. versionadded:: 3.4.0
Returns
-------
pyspark.pandas.Series or pyspark.pandas.DataFrame
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2],
... 'B': [np.nan, 2, 3, 4, 5],
... 'C': [1, 2, 1, 1, 2],
... 'D': [True, False, True, False, True]})
Groupby one column and return the mean of the remaining columns in
each group.
>>> df.groupby('A').mean().sort_index() # doctest: +NORMALIZE_WHITESPACE
B C D
A
1 3.0 1.333333 0.333333
2 4.0 1.500000 1.000000
"""
self._validate_agg_columns(numeric_only=numeric_only, function_name="median")
return self._reduce_for_stat_function(
F.mean, accepted_spark_types=(NumericType,), bool_to_numeric=True
)
# TODO: 'q' accepts list like type
def quantile(self, q: float = 0.5, accuracy: int = 10000) -> FrameLike:
"""
Return group values at the given quantile.
.. versionadded:: 3.4.0
Parameters
----------
q : float, default 0.5 (50% quantile)
Value between 0 and 1 providing the quantile to compute.
accuracy : int, optional
Default accuracy of approximation. Larger value means better accuracy.
The relative error can be deduced by 1.0 / accuracy.
This is a panda-on-Spark specific parameter.
Returns
-------
pyspark.pandas.Series or pyspark.pandas.DataFrame
Return type determined by caller of GroupBy object.
Notes
-----
`quantile` in pandas-on-Spark are using distributed percentile approximation
algorithm unlike pandas, the result might be different with pandas, also
`interpolation` parameter is not supported yet.
See Also
--------
pyspark.pandas.Series.quantile
pyspark.pandas.DataFrame.quantile
pyspark.sql.functions.percentile_approx
Examples
--------
>>> df = ps.DataFrame([
... ['a', 1], ['a', 2], ['a', 3],
... ['b', 1], ['b', 3], ['b', 5]
... ], columns=['key', 'val'])
Groupby one column and return the quantile of the remaining columns in
each group.
>>> df.groupby('key').quantile()
val
key
a 2.0
b 3.0
"""
if is_list_like(q):
raise NotImplementedError("q doesn't support for list like type for now")
if not is_number(q):
raise TypeError("must be real number, not %s" % type(q).__name__)
if not 0 <= q <= 1:
raise ValueError("'q' must be between 0 and 1. Got '%s' instead" % q)
return self._reduce_for_stat_function(
lambda col: F.percentile_approx(col.cast(DoubleType()), q, accuracy),
accepted_spark_types=(NumericType, BooleanType),
bool_to_numeric=True,
)
def min(self, numeric_only: Optional[bool] = False, min_count: int = -1) -> FrameLike:
"""
Compute min of group values.
.. versionadded:: 3.3.0
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
.. versionadded:: 3.4.0
min_count : bool, default -1
The required number of valid values to perform the operation. If fewer
than min_count non-NA values are present the result will be NA.
.. versionadded:: 3.4.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "a", "b", "a"]})
>>> df.groupby("A").min().sort_index()
B C D
A
1 False 3 a
2 False 4 a
Include only float, int, boolean columns when set numeric_only True.
>>> df.groupby("A").min(numeric_only=True).sort_index()
B C
A
1 False 3
2 False 4
>>> df.groupby("D").min().sort_index()
A B C
D
a 1 False 3
b 1 False 3
>>> df.groupby("D").min(min_count=3).sort_index()
A B C
D
a 1.0 False 3.0
b NaN None NaN
"""
if not isinstance(min_count, int):
raise TypeError("min_count must be integer")
return self._reduce_for_stat_function(
F.min,
accepted_spark_types=(NumericType, BooleanType) if numeric_only else None,
min_count=min_count,
)
# TODO: sync the doc.
def std(self, ddof: int = 1) -> FrameLike:
"""
Compute standard deviation of groups, excluding missing values.
.. versionadded:: 3.3.0
Parameters
----------
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
.. versionchanged:: 3.4.0
Supported including arbitary integers.
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "b", "b", "a"]})
>>> df.groupby("A").std()
B C
A
1 0.707107 0.0
2 0.707107 0.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
"""
if not isinstance(ddof, int):
raise TypeError("ddof must be integer")
# Raise the TypeError when all aggregation columns are of unaccepted data types
any_accepted = any(
isinstance(_agg_col.spark.data_type, (NumericType, BooleanType))
for _agg_col in self._agg_columns
)
if not any_accepted:
raise TypeError(
"Unaccepted data types of aggregation columns; numeric or bool expected."
)
def std(col: Column) -> Column:
return SF.stddev(col, ddof)
return self._reduce_for_stat_function(
std,
accepted_spark_types=(NumericType,),
bool_to_numeric=True,
)
def sum(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> FrameLike:
"""
Compute sum of group values
.. versionadded:: 3.3.0
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data.
It takes no effect since only numeric columns can be support here.
.. versionadded:: 3.4.0
min_count : int, default 0
The required number of valid values to perform the operation.
If fewer than min_count non-NA values are present the result will be NA.
.. versionadded:: 3.4.0
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "a", "b", "a"]})
>>> df.groupby("A").sum().sort_index()
B C
A
1 1 6
2 1 8
>>> df.groupby("D").sum().sort_index()
A B C
D
a 5 2 11
b 1 0 3
>>> df.groupby("D").sum(min_count=3).sort_index()
A B C
D
a 5.0 2.0 11.0
b NaN NaN NaN
Notes
-----
There is a behavior difference between pandas-on-Spark and pandas:
* when there is a non-numeric aggregation column, it will be ignored
even if `numeric_only` is False.
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
"""
if numeric_only is not None and not isinstance(numeric_only, bool):
raise TypeError("numeric_only must be None or bool")
if not isinstance(min_count, int):
raise TypeError("min_count must be integer")
if numeric_only is not None and not numeric_only:
unsupported = [
col.name
for col in self._agg_columns
if not isinstance(col.spark.data_type, (NumericType, BooleanType))
]
if len(unsupported) > 0:
log_advice(
"GroupBy.sum() can only support numeric and bool columns even if"
f"numeric_only=False, skip unsupported columns: {unsupported}"
)
return self._reduce_for_stat_function(
F.sum,
accepted_spark_types=(NumericType, BooleanType),
bool_to_numeric=True,
min_count=min_count,
)
# TODO: sync the doc.
def var(self, ddof: int = 1) -> FrameLike:
"""
Compute variance of groups, excluding missing values.
.. versionadded:: 3.3.0
Parameters
----------
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
.. versionchanged:: 3.4.0
Supported including arbitary integers.
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 2], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "b", "b", "a"]})
>>> df.groupby("A").var()
B C
A
1 0.5 0.0
2 0.5 0.0
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
"""
if not isinstance(ddof, int):
raise TypeError("ddof must be integer")
def var(col: Column) -> Column:
return SF.var(col, ddof)
return self._reduce_for_stat_function(
var,
accepted_spark_types=(NumericType,),
bool_to_numeric=True,
)
def skew(self) -> FrameLike:
"""
Compute skewness of groups, excluding missing values.
.. versionadded:: 3.4.0
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 1], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "b", "b", "a"]})
>>> df.groupby("A").skew()
B C
A
1 -1.732051 1.732051
2 NaN NaN
See Also
--------
pyspark.pandas.Series.groupby
pyspark.pandas.DataFrame.groupby
"""
return self._reduce_for_stat_function(
SF.skew,
accepted_spark_types=(NumericType,),
bool_to_numeric=True,
)
# TODO: 'axis', 'skipna', 'level' parameter should be implemented.
def mad(self) -> FrameLike:
"""
Compute mean absolute deviation of groups, excluding missing values.
.. versionadded:: 3.4.0
.. deprecated:: 3.4.0
Examples
--------
>>> df = ps.DataFrame({"A": [1, 2, 1, 1], "B": [True, False, False, True],
... "C": [3, 4, 3, 4], "D": ["a", "b", "b", "a"]})
>>> df.groupby("A").mad()
B C
A