-
-
Notifications
You must be signed in to change notification settings - Fork 18.3k
/
Copy pathgeneric.py
2855 lines (2453 loc) · 94.7 KB
/
generic.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
"""
Define the SeriesGroupBy and DataFrameGroupBy
classes that hold the groupby interfaces (and some implementations).
These are user facing as the result of the ``df.groupby(...)`` operations,
which here returns a DataFrameGroupBy object.
"""
from __future__ import annotations
from collections import abc
from functools import partial
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
NamedTuple,
TypeVar,
Union,
cast,
)
import warnings
import numpy as np
from pandas._libs import (
Interval,
lib,
)
from pandas._libs.hashtable import duplicated
from pandas.errors import SpecificationError
from pandas.util._decorators import (
Appender,
Substitution,
doc,
)
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import (
ensure_int64,
is_bool,
is_dict_like,
is_integer_dtype,
is_list_like,
is_numeric_dtype,
is_scalar,
)
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
IntervalDtype,
)
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import (
isna,
notna,
)
from pandas.core import algorithms
from pandas.core.apply import (
GroupByApply,
maybe_mangle_lambdas,
reconstruct_func,
validate_func_kwargs,
warn_alias_replacement,
)
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.groupby import (
base,
ops,
)
from pandas.core.groupby.groupby import (
GroupBy,
GroupByPlot,
_agg_template_frame,
_agg_template_series,
_apply_docs,
_transform_template,
)
from pandas.core.indexes.api import (
Index,
MultiIndex,
all_indexes_same,
default_index,
)
from pandas.core.series import Series
from pandas.core.sorting import get_group_index
from pandas.core.util.numba_ import maybe_use_numba
from pandas.plotting import boxplot_frame_groupby
if TYPE_CHECKING:
from collections.abc import (
Hashable,
Mapping,
Sequence,
)
from pandas._typing import (
ArrayLike,
Axis,
AxisInt,
CorrelationMethod,
FillnaOptions,
IndexLabel,
Manager,
Manager2D,
SingleManager,
TakeIndexer,
)
from pandas import Categorical
from pandas.core.generic import NDFrame
# TODO(typing) the return value on this callable should be any *scalar*.
AggScalar = Union[str, Callable[..., Any]]
# TODO: validate types on ScalarResult and move to _typing
# Blocked from using by https://github.com/python/mypy/issues/1484
# See note at _mangle_lambda_list
ScalarResult = TypeVar("ScalarResult")
class NamedAgg(NamedTuple):
"""
Helper for column specific aggregation with control over output column names.
Subclass of typing.NamedTuple.
Parameters
----------
column : Hashable
Column label in the DataFrame to apply aggfunc.
aggfunc : function or str
Function to apply to the provided column. If string, the name of a built-in
pandas function.
Examples
--------
>>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], 1: [10, 11, 12]})
>>> agg_a = pd.NamedAgg(column="a", aggfunc="min")
>>> agg_1 = pd.NamedAgg(column=1, aggfunc=lambda x: np.mean(x))
>>> df.groupby("key").agg(result_a=agg_a, result_1=agg_1)
result_a result_1
key
1 -1 10.5
2 1 12.0
"""
column: Hashable
aggfunc: AggScalar
class SeriesGroupBy(GroupBy[Series]):
def _wrap_agged_manager(self, mgr: Manager) -> Series:
out = self.obj._constructor_from_mgr(mgr, axes=mgr.axes)
out._name = self.obj.name
return out
def _get_data_to_aggregate(
self, *, numeric_only: bool = False, name: str | None = None
) -> SingleManager:
ser = self._obj_with_exclusions
single = ser._mgr
if numeric_only and not is_numeric_dtype(ser.dtype):
# GH#41291 match Series behavior
kwd_name = "numeric_only"
raise TypeError(
f"Cannot use {kwd_name}=True with "
f"{type(self).__name__}.{name} and non-numeric dtypes."
)
return single
_agg_examples_doc = dedent(
"""
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.groupby([1, 1, 2, 2]).min()
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg('min')
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg(['min', 'max'])
min max
1 1 2
2 3 4
The output column names can be controlled by passing
the desired column names and aggregations as keyword arguments.
>>> s.groupby([1, 1, 2, 2]).agg(
... minimum='min',
... maximum='max',
... )
minimum maximum
1 1 2
2 3 4
.. versionchanged:: 1.3.0
The resulting dtype will reflect the return value of the aggregating function.
>>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min())
1 1.0
2 3.0
dtype: float64
"""
)
@Appender(
_apply_docs["template"].format(
input="series", examples=_apply_docs["series_examples"]
)
)
def apply(self, func, *args, **kwargs) -> Series:
return super().apply(func, *args, **kwargs)
@doc(_agg_template_series, examples=_agg_examples_doc, klass="Series")
def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs):
relabeling = func is None
columns = None
if relabeling:
columns, func = validate_func_kwargs(kwargs)
kwargs = {}
if isinstance(func, str):
if maybe_use_numba(engine) and engine is not None:
# Not all agg functions support numba, only propagate numba kwargs
# if user asks for numba, and engine is not None
# (if engine is None, the called function will handle the case where
# numba is requested via the global option)
kwargs["engine"] = engine
if engine_kwargs is not None:
kwargs["engine_kwargs"] = engine_kwargs
return getattr(self, func)(*args, **kwargs)
elif isinstance(func, abc.Iterable):
# Catch instances of lists / tuples
# but not the class list / tuple itself.
func = maybe_mangle_lambdas(func)
kwargs["engine"] = engine
kwargs["engine_kwargs"] = engine_kwargs
ret = self._aggregate_multiple_funcs(func, *args, **kwargs)
if relabeling:
# columns is not narrowed by mypy from relabeling flag
assert columns is not None # for mypy
ret.columns = columns
if not self.as_index:
ret = ret.reset_index()
return ret
else:
cyfunc = com.get_cython_func(func)
if cyfunc and not args and not kwargs:
warn_alias_replacement(self, func, cyfunc)
return getattr(self, cyfunc)()
if maybe_use_numba(engine):
return self._aggregate_with_numba(
func, *args, engine_kwargs=engine_kwargs, **kwargs
)
if self.ngroups == 0:
# e.g. test_evaluate_with_empty_groups without any groups to
# iterate over, we have no output on which to do dtype
# inference. We default to using the existing dtype.
# xref GH#51445
obj = self._obj_with_exclusions
return self.obj._constructor(
[],
name=self.obj.name,
index=self._grouper.result_index,
dtype=obj.dtype,
)
if self._grouper.nkeys > 1:
return self._python_agg_general(func, *args, **kwargs)
try:
return self._python_agg_general(func, *args, **kwargs)
except KeyError:
# KeyError raised in test_groupby.test_basic is bc the func does
# a dictionary lookup on group.name, but group name is not
# pinned in _python_agg_general, only in _aggregate_named
result = self._aggregate_named(func, *args, **kwargs)
warnings.warn(
"Pinning the groupby key to each group in "
f"{type(self).__name__}.agg is deprecated, and cases that "
"relied on it will raise in a future version. "
"If your operation requires utilizing the groupby keys, "
"iterate over the groupby object instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
# result is a dict whose keys are the elements of result_index
result = Series(result, index=self._grouper.result_index)
result = self._wrap_aggregated_output(result)
return result
agg = aggregate
def _python_agg_general(self, func, *args, **kwargs):
orig_func = func
func = com.is_builtin_func(func)
if orig_func != func:
alias = com._builtin_table_alias[func]
warn_alias_replacement(self, orig_func, alias)
f = lambda x: func(x, *args, **kwargs)
obj = self._obj_with_exclusions
result = self._grouper.agg_series(obj, f)
res = obj._constructor(result, name=obj.name)
return self._wrap_aggregated_output(res)
def _aggregate_multiple_funcs(self, arg, *args, **kwargs) -> DataFrame:
if isinstance(arg, dict):
if self.as_index:
# GH 15931
raise SpecificationError("nested renamer is not supported")
else:
# GH#50684 - This accidentally worked in 1.x
msg = (
"Passing a dictionary to SeriesGroupBy.agg is deprecated "
"and will raise in a future version of pandas. Pass a list "
"of aggregations instead."
)
warnings.warn(
message=msg,
category=FutureWarning,
stacklevel=find_stack_level(),
)
arg = list(arg.items())
elif any(isinstance(x, (tuple, list)) for x in arg):
arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg]
else:
# list of functions / function names
columns = (com.get_callable_name(f) or f for f in arg)
arg = zip(columns, arg)
results: dict[base.OutputKey, DataFrame | Series] = {}
with com.temp_setattr(self, "as_index", True):
# Combine results using the index, need to adjust index after
# if as_index=False (GH#50724)
for idx, (name, func) in enumerate(arg):
key = base.OutputKey(label=name, position=idx)
results[key] = self.aggregate(func, *args, **kwargs)
if any(isinstance(x, DataFrame) for x in results.values()):
from pandas import concat
res_df = concat(
results.values(), axis=1, keys=[key.label for key in results]
)
return res_df
indexed_output = {key.position: val for key, val in results.items()}
output = self.obj._constructor_expanddim(indexed_output, index=None)
output.columns = Index(key.label for key in results)
return output
def _wrap_applied_output(
self,
data: Series,
values: list[Any],
not_indexed_same: bool = False,
is_transform: bool = False,
) -> DataFrame | Series:
"""
Wrap the output of SeriesGroupBy.apply into the expected result.
Parameters
----------
data : Series
Input data for groupby operation.
values : List[Any]
Applied output for each group.
not_indexed_same : bool, default False
Whether the applied outputs are not indexed the same as the group axes.
Returns
-------
DataFrame or Series
"""
if len(values) == 0:
# GH #6265
if is_transform:
# GH#47787 see test_group_on_empty_multiindex
res_index = data.index
else:
res_index = self._grouper.result_index
return self.obj._constructor(
[],
name=self.obj.name,
index=res_index,
dtype=data.dtype,
)
assert values is not None
if isinstance(values[0], dict):
# GH #823 #24880
index = self._grouper.result_index
res_df = self.obj._constructor_expanddim(values, index=index)
res_df = self._reindex_output(res_df)
# if self.observed is False,
# keep all-NaN rows created while re-indexing
res_ser = res_df.stack(future_stack=True)
res_ser.name = self.obj.name
return res_ser
elif isinstance(values[0], (Series, DataFrame)):
result = self._concat_objects(
values,
not_indexed_same=not_indexed_same,
is_transform=is_transform,
)
if isinstance(result, Series):
result.name = self.obj.name
if not self.as_index and not_indexed_same:
result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))
return result
else:
# GH #6265 #24880
result = self.obj._constructor(
data=values, index=self._grouper.result_index, name=self.obj.name
)
if not self.as_index:
result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))
return self._reindex_output(result)
def _aggregate_named(self, func, *args, **kwargs):
# Note: this is very similar to _aggregate_series_pure_python,
# but that does not pin group.name
result = {}
initialized = False
for name, group in self._grouper.get_iterator(
self._obj_with_exclusions, axis=self.axis
):
# needed for pandas/tests/groupby/test_groupby.py::test_basic_aggregations
object.__setattr__(group, "name", name)
output = func(group, *args, **kwargs)
output = ops.extract_result(output)
if not initialized:
# We only do this validation on the first iteration
ops.check_result_array(output, group.dtype)
initialized = True
result[name] = output
return result
__examples_series_doc = dedent(
"""
>>> ser = pd.Series([390.0, 350.0, 30.0, 20.0],
... index=["Falcon", "Falcon", "Parrot", "Parrot"],
... name="Max Speed")
>>> grouped = ser.groupby([1, 1, 2, 2])
>>> grouped.transform(lambda x: (x - x.mean()) / x.std())
Falcon 0.707107
Falcon -0.707107
Parrot 0.707107
Parrot -0.707107
Name: Max Speed, dtype: float64
Broadcast result of the transformation
>>> grouped.transform(lambda x: x.max() - x.min())
Falcon 40.0
Falcon 40.0
Parrot 10.0
Parrot 10.0
Name: Max Speed, dtype: float64
>>> grouped.transform("mean")
Falcon 370.0
Falcon 370.0
Parrot 25.0
Parrot 25.0
Name: Max Speed, dtype: float64
.. versionchanged:: 1.3.0
The resulting dtype will reflect the return value of the passed ``func``,
for example:
>>> grouped.transform(lambda x: x.astype(int).max())
Falcon 390
Falcon 390
Parrot 30
Parrot 30
Name: Max Speed, dtype: int64
"""
)
@Substitution(klass="Series", example=__examples_series_doc)
@Appender(_transform_template)
def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
return self._transform(
func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
)
def _cython_transform(
self, how: str, numeric_only: bool = False, axis: AxisInt = 0, **kwargs
):
assert axis == 0 # handled by caller
obj = self._obj_with_exclusions
try:
result = self._grouper._cython_operation(
"transform", obj._values, how, axis, **kwargs
)
except NotImplementedError as err:
# e.g. test_groupby_raises_string
raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err
return obj._constructor(result, index=self.obj.index, name=obj.name)
def _transform_general(
self, func: Callable, engine, engine_kwargs, *args, **kwargs
) -> Series:
"""
Transform with a callable `func`.
"""
if maybe_use_numba(engine):
return self._transform_with_numba(
func, *args, engine_kwargs=engine_kwargs, **kwargs
)
assert callable(func)
klass = type(self.obj)
results = []
for name, group in self._grouper.get_iterator(
self._obj_with_exclusions, axis=self.axis
):
# this setattr is needed for test_transform_lambda_with_datetimetz
object.__setattr__(group, "name", name)
res = func(group, *args, **kwargs)
results.append(klass(res, index=group.index))
# check for empty "results" to avoid concat ValueError
if results:
from pandas.core.reshape.concat import concat
concatenated = concat(results)
result = self._set_result_index_ordered(concatenated)
else:
result = self.obj._constructor(dtype=np.float64)
result.name = self.obj.name
return result
def filter(self, func, dropna: bool = True, *args, **kwargs):
"""
Filter elements from groups that don't satisfy a criterion.
Elements from groups are filtered if they do not satisfy the
boolean criterion specified by func.
Parameters
----------
func : function
Criterion to apply to each group. Should return True or False.
dropna : bool
Drop groups that do not pass the filter. True by default; if False,
groups that evaluate False are filled with NaNs.
Returns
-------
Series
Notes
-----
Functions that mutate the passed object can produce unexpected
behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
for more details.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> df.groupby('A').B.filter(lambda x: x.mean() > 3.)
1 2
3 4
5 6
Name: B, dtype: int64
"""
if isinstance(func, str):
wrapper = lambda x: getattr(x, func)(*args, **kwargs)
else:
wrapper = lambda x: func(x, *args, **kwargs)
# Interpret np.nan as False.
def true_and_notna(x) -> bool:
b = wrapper(x)
return notna(b) and b
try:
indices = [
self._get_index(name)
for name, group in self._grouper.get_iterator(
self._obj_with_exclusions, axis=self.axis
)
if true_and_notna(group)
]
except (ValueError, TypeError) as err:
raise TypeError("the filter must return a boolean result") from err
filtered = self._apply_filter(indices, dropna)
return filtered
def nunique(self, dropna: bool = True) -> Series | DataFrame:
"""
Return number of unique elements in the group.
Returns
-------
Series
Number of unique values within each group.
Examples
--------
For SeriesGroupby:
>>> lst = ['a', 'a', 'b', 'b']
>>> ser = pd.Series([1, 2, 3, 3], index=lst)
>>> ser
a 1
a 2
b 3
b 3
dtype: int64
>>> ser.groupby(level=0).nunique()
a 2
b 1
dtype: int64
For Resampler:
>>> ser = pd.Series([1, 2, 3, 3], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 3
dtype: int64
>>> ser.resample('MS').nunique()
2023-01-01 2
2023-02-01 1
Freq: MS, dtype: int64
"""
ids, _, ngroups = self._grouper.group_info
val = self.obj._values
codes, uniques = algorithms.factorize(val, use_na_sentinel=dropna, sort=False)
if self._grouper.has_dropped_na:
mask = ids >= 0
ids = ids[mask]
codes = codes[mask]
group_index = get_group_index(
labels=[ids, codes],
shape=(ngroups, len(uniques)),
sort=False,
xnull=dropna,
)
if dropna:
mask = group_index >= 0
if (~mask).any():
ids = ids[mask]
group_index = group_index[mask]
mask = duplicated(group_index, "first")
res = np.bincount(ids[~mask], minlength=ngroups)
res = ensure_int64(res)
ri = self._grouper.result_index
result: Series | DataFrame = self.obj._constructor(
res, index=ri, name=self.obj.name
)
if not self.as_index:
result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))
return self._reindex_output(result, fill_value=0)
@doc(Series.describe)
def describe(self, percentiles=None, include=None, exclude=None) -> Series:
return super().describe(
percentiles=percentiles, include=include, exclude=exclude
)
def value_counts(
self,
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
bins=None,
dropna: bool = True,
) -> Series | DataFrame:
name = "proportion" if normalize else "count"
if bins is None:
result = self._value_counts(
normalize=normalize, sort=sort, ascending=ascending, dropna=dropna
)
result.name = name
return result
from pandas.core.reshape.merge import get_join_indexers
from pandas.core.reshape.tile import cut
ids, _, _ = self._grouper.group_info
val = self.obj._values
index_names = self._grouper.names + [self.obj.name]
if isinstance(val.dtype, CategoricalDtype) or (
bins is not None and not np.iterable(bins)
):
# scalar bins cannot be done at top level
# in a backward compatible way
# GH38672 relates to categorical dtype
ser = self.apply(
Series.value_counts,
normalize=normalize,
sort=sort,
ascending=ascending,
bins=bins,
)
ser.name = name
ser.index.names = index_names
return ser
# groupby removes null keys from groupings
mask = ids != -1
ids, val = ids[mask], val[mask]
lab: Index | np.ndarray
if bins is None:
lab, lev = algorithms.factorize(val, sort=True)
llab = lambda lab, inc: lab[inc]
else:
# lab is a Categorical with categories an IntervalIndex
cat_ser = cut(Series(val, copy=False), bins, include_lowest=True)
cat_obj = cast("Categorical", cat_ser._values)
lev = cat_obj.categories
lab = lev.take(
cat_obj.codes,
allow_fill=True,
fill_value=lev._na_value,
)
llab = lambda lab, inc: lab[inc]._multiindex.codes[-1]
if isinstance(lab.dtype, IntervalDtype):
# TODO: should we do this inside II?
lab_interval = cast(Interval, lab)
sorter = np.lexsort((lab_interval.left, lab_interval.right, ids))
else:
sorter = np.lexsort((lab, ids))
ids, lab = ids[sorter], lab[sorter]
# group boundaries are where group ids change
idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0]
idx = np.r_[0, idchanges]
if not len(ids):
idx = idchanges
# new values are where sorted labels change
lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1))
inc = np.r_[True, lchanges]
if not len(val):
inc = lchanges
inc[idx] = True # group boundaries are also new values
out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts
# num. of times each group should be repeated
rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx))
# multi-index components
codes = self._grouper.reconstructed_codes
codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)]
levels = [ping._group_index for ping in self._grouper.groupings] + [lev]
if dropna:
mask = codes[-1] != -1
if mask.all():
dropna = False
else:
out, codes = out[mask], [level_codes[mask] for level_codes in codes]
if normalize:
out = out.astype("float")
d = np.diff(np.r_[idx, len(ids)])
if dropna:
m = ids[lab == -1]
np.add.at(d, m, -1)
acc = rep(d)[mask]
else:
acc = rep(d)
out /= acc
if sort and bins is None:
cat = ids[inc][mask] if dropna else ids[inc]
sorter = np.lexsort((out if ascending else -out, cat))
out, codes[-1] = out[sorter], codes[-1][sorter]
if bins is not None:
# for compat. with libgroupby.value_counts need to ensure every
# bin is present at every index level, null filled with zeros
diff = np.zeros(len(out), dtype="bool")
for level_codes in codes[:-1]:
diff |= np.r_[True, level_codes[1:] != level_codes[:-1]]
ncat, nbin = diff.sum(), len(levels[-1])
left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)]
right = [diff.cumsum() - 1, codes[-1]]
# error: Argument 1 to "get_join_indexers" has incompatible type
# "List[ndarray[Any, Any]]"; expected "List[Union[Union[ExtensionArray,
# ndarray[Any, Any]], Index, Series]]
_, idx = get_join_indexers(
left, # type: ignore[arg-type]
right, # type: ignore[arg-type]
sort=False,
how="left",
)
if idx is not None:
out = np.where(idx != -1, out[idx], 0)
if sort:
sorter = np.lexsort((out if ascending else -out, left[0]))
out, left[-1] = out[sorter], left[-1][sorter]
# build the multi-index w/ full levels
def build_codes(lev_codes: np.ndarray) -> np.ndarray:
return np.repeat(lev_codes[diff], nbin)
codes = [build_codes(lev_codes) for lev_codes in codes[:-1]]
codes.append(left[-1])
mi = MultiIndex(
levels=levels, codes=codes, names=index_names, verify_integrity=False
)
if is_integer_dtype(out.dtype):
out = ensure_int64(out)
result = self.obj._constructor(out, index=mi, name=name)
if not self.as_index:
result = result.reset_index()
return result
def fillna(
self,
value: object | ArrayLike | None = None,
method: FillnaOptions | None = None,
axis: Axis | None | lib.NoDefault = lib.no_default,
inplace: bool = False,
limit: int | None = None,
downcast: dict | None | lib.NoDefault = lib.no_default,
) -> Series | None:
"""
Fill NA/NaN values using the specified method within groups.
.. deprecated:: 2.2.0
This method is deprecated and will be removed in a future version.
Use the :meth:`.SeriesGroupBy.ffill` or :meth:`.SeriesGroupBy.bfill`
for forward or backward filling instead. If you want to fill with a
single value, use :meth:`Series.fillna` instead.
Parameters
----------
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
each index (for a Series) or column (for a DataFrame). Values not
in the dict/Series/DataFrame will not be filled. This value cannot
be a list. Users wanting to use the ``value`` argument and not ``method``
should prefer :meth:`.Series.fillna` as this
will produce the same result and be more performant.
method : {{'bfill', 'ffill', None}}, default None
Method to use for filling holes. ``'ffill'`` will propagate
the last valid observation forward within a group.
``'bfill'`` will use next valid observation to fill the gap.
axis : {0 or 'index', 1 or 'columns'}
Unused, only for compatibility with :meth:`DataFrameGroupBy.fillna`.
inplace : bool, default False
Broken. Do not set to True.
limit : int, default None
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill within a group. In other words,
if there is a gap with more than this number of consecutive NaNs,
it will only be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
downcast : dict, default is None
A dict of item->dtype of what to downcast if possible,
or the string 'infer' which will try to downcast to an appropriate
equal type (e.g. float64 to int64 if possible).
Returns
-------
Series
Object with missing values filled within groups.
See Also
--------
ffill : Forward fill values within a group.
bfill : Backward fill values within a group.
Examples
--------
For SeriesGroupBy:
>>> lst = ['cat', 'cat', 'cat', 'mouse', 'mouse']
>>> ser = pd.Series([1, None, None, 2, None], index=lst)
>>> ser
cat 1.0
cat NaN
cat NaN
mouse 2.0
mouse NaN
dtype: float64
>>> ser.groupby(level=0).fillna(0, limit=1)
cat 1.0
cat 0.0
cat NaN
mouse 2.0
mouse 0.0
dtype: float64
"""
warnings.warn(
f"{type(self).__name__}.fillna is deprecated and "
"will be removed in a future version. Use obj.ffill() or obj.bfill() "
"for forward or backward filling instead. If you want to fill with a "
f"single value, use {type(self.obj).__name__}.fillna instead",
FutureWarning,
stacklevel=find_stack_level(),
)
result = self._op_via_apply(
"fillna",
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
return result
def take(
self,
indices: TakeIndexer,
axis: Axis | lib.NoDefault = lib.no_default,
**kwargs,
) -> Series:
"""
Return the elements in the given *positional* indices in each group.
This means that we are not indexing according to actual values in
the index attribute of the object. We are indexing according to the
actual position of the element in the object.
If a requested index does not exist for some group, this method will raise.
To get similar behavior that ignores indices that don't exist, see
:meth:`.SeriesGroupBy.nth`.
Parameters
----------
indices : array-like
An array of ints indicating which positions to take in each group.
axis : {0 or 'index', 1 or 'columns', None}, default 0