19
19
Iterable ,
20
20
List ,
21
21
Mapping ,
22
+ Optional ,
22
23
Sequence ,
23
24
Tuple ,
24
25
Type ,
30
31
import numpy as np
31
32
32
33
from pandas ._libs import lib
33
- from pandas ._typing import FrameOrSeries
34
+ from pandas ._typing import FrameOrSeries , FrameOrSeriesUnion
34
35
from pandas .util ._decorators import Appender , Substitution , doc
35
36
36
37
from pandas .core .dtypes .cast import (
@@ -413,12 +414,31 @@ def _wrap_transformed_output(
413
414
assert isinstance (result , Series )
414
415
return result
415
416
416
- def _wrap_applied_output (self , keys , values , not_indexed_same = False ):
417
+ def _wrap_applied_output (
418
+ self , keys : Index , values : Optional [List [Any ]], not_indexed_same : bool = False
419
+ ) -> FrameOrSeriesUnion :
420
+ """
421
+ Wrap the output of SeriesGroupBy.apply into the expected result.
422
+
423
+ Parameters
424
+ ----------
425
+ keys : Index
426
+ Keys of groups that Series was grouped by.
427
+ values : Optional[List[Any]]
428
+ Applied output for each group.
429
+ not_indexed_same : bool, default False
430
+ Whether the applied outputs are not indexed the same as the group axes.
431
+
432
+ Returns
433
+ -------
434
+ DataFrame or Series
435
+ """
417
436
if len (keys ) == 0 :
418
437
# GH #6265
419
438
return self .obj ._constructor (
420
439
[], name = self ._selection_name , index = keys , dtype = np .float64
421
440
)
441
+ assert values is not None
422
442
423
443
def _get_index () -> Index :
424
444
if self .grouper .nkeys > 1 :
@@ -430,19 +450,15 @@ def _get_index() -> Index:
430
450
if isinstance (values [0 ], dict ):
431
451
# GH #823 #24880
432
452
index = _get_index ()
433
- result = self ._reindex_output (
453
+ result : FrameOrSeriesUnion = self ._reindex_output (
434
454
self .obj ._constructor_expanddim (values , index = index )
435
455
)
436
456
# if self.observed is False,
437
457
# keep all-NaN rows created while re-indexing
438
458
result = result .stack (dropna = self .observed )
439
459
result .name = self ._selection_name
440
460
return result
441
-
442
- if isinstance (values [0 ], Series ):
443
- return self ._concat_objects (keys , values , not_indexed_same = not_indexed_same )
444
- elif isinstance (values [0 ], DataFrame ):
445
- # possible that Series -> DataFrame by applied function
461
+ elif isinstance (values [0 ], (Series , DataFrame )):
446
462
return self ._concat_objects (keys , values , not_indexed_same = not_indexed_same )
447
463
else :
448
464
# GH #6265 #24880
0 commit comments