4
4
5
5
import builtins
6
6
import textwrap
7
- from typing import Any , Callable , Dict , FrozenSet , Optional , Union
7
+ from typing import Any , Callable , Dict , FrozenSet , List , Optional , Union , cast
8
8
9
9
import numpy as np
10
10
11
11
import pandas ._libs .lib as lib
12
+ from pandas ._typing import AggFuncType , AggFuncTypeBase , Label
12
13
from pandas .compat import PYPY
13
14
from pandas .compat .numpy import function as nv
14
15
from pandas .errors import AbstractMethodError
@@ -278,7 +279,7 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
278
279
f"'{ arg } ' is not a valid function for '{ type (self ).__name__ } ' object"
279
280
)
280
281
281
- def _aggregate (self , arg , * args , ** kwargs ):
282
+ def _aggregate (self , arg : AggFuncType , * args , ** kwargs ):
282
283
"""
283
284
provide an implementation for the aggregators
284
285
@@ -311,13 +312,13 @@ def _aggregate(self, arg, *args, **kwargs):
311
312
if _axis != 0 : # pragma: no cover
312
313
raise ValueError ("Can only pass dict with axis=0" )
313
314
314
- obj = self ._selected_obj
315
+ selected_obj = self ._selected_obj
315
316
316
317
# if we have a dict of any non-scalars
317
318
# eg. {'A' : ['mean']}, normalize all to
318
319
# be list-likes
319
320
if any (is_aggregator (x ) for x in arg .values ()):
320
- new_arg = {}
321
+ new_arg : Dict [ Label , Union [ AggFuncTypeBase , List [ AggFuncTypeBase ]]] = {}
321
322
for k , v in arg .items ():
322
323
if not isinstance (v , (tuple , list , dict )):
323
324
new_arg [k ] = [v ]
@@ -336,9 +337,12 @@ def _aggregate(self, arg, *args, **kwargs):
336
337
# {'ra' : { 'A' : 'mean' }}
337
338
if isinstance (v , dict ):
338
339
raise SpecificationError ("nested renamer is not supported" )
339
- elif isinstance (obj , ABCSeries ):
340
+ elif isinstance (selected_obj , ABCSeries ):
340
341
raise SpecificationError ("nested renamer is not supported" )
341
- elif isinstance (obj , ABCDataFrame ) and k not in obj .columns :
342
+ elif (
343
+ isinstance (selected_obj , ABCDataFrame )
344
+ and k not in selected_obj .columns
345
+ ):
342
346
raise KeyError (f"Column '{ k } ' does not exist!" )
343
347
344
348
arg = new_arg
@@ -347,10 +351,12 @@ def _aggregate(self, arg, *args, **kwargs):
347
351
# deprecation of renaming keys
348
352
# GH 15931
349
353
keys = list (arg .keys ())
350
- if isinstance (obj , ABCDataFrame ) and len (
351
- obj .columns .intersection (keys )
354
+ if isinstance (selected_obj , ABCDataFrame ) and len (
355
+ selected_obj .columns .intersection (keys )
352
356
) != len (keys ):
353
- cols = sorted (set (keys ) - set (obj .columns .intersection (keys )))
357
+ cols = sorted (
358
+ set (keys ) - set (selected_obj .columns .intersection (keys ))
359
+ )
354
360
raise SpecificationError (f"Column(s) { cols } do not exist" )
355
361
356
362
from pandas .core .reshape .concat import concat
@@ -370,7 +376,7 @@ def _agg_2dim(how):
370
376
"""
371
377
aggregate a 2-dim with how
372
378
"""
373
- colg = self ._gotitem (self ._selection , ndim = 2 , subset = obj )
379
+ colg = self ._gotitem (self ._selection , ndim = 2 , subset = selected_obj )
374
380
return colg .aggregate (how )
375
381
376
382
def _agg (arg , func ):
@@ -385,7 +391,6 @@ def _agg(arg, func):
385
391
386
392
# set the final keys
387
393
keys = list (arg .keys ())
388
- result = {}
389
394
390
395
if self ._selection is not None :
391
396
@@ -473,7 +478,11 @@ def is_any_frame() -> bool:
473
478
# we have a dict of scalars
474
479
475
480
# GH 36212 use name only if self is a series
476
- name = self .name if (self .ndim == 1 ) else None
481
+ if self .ndim == 1 :
482
+ self = cast ("Series" , self )
483
+ name = self .name
484
+ else :
485
+ name = None
477
486
478
487
result = Series (result , name = name )
479
488
@@ -484,9 +493,10 @@ def is_any_frame() -> bool:
484
493
else :
485
494
result = None
486
495
487
- f = self ._get_cython_func (arg )
488
- if f and not args and not kwargs :
489
- return getattr (self , f )(), None
496
+ if callable (arg ):
497
+ f = self ._get_cython_func (arg )
498
+ if f and not args and not kwargs :
499
+ return getattr (self , f )(), None
490
500
491
501
# caller can react
492
502
return result , True
@@ -498,17 +508,17 @@ def _aggregate_multiple_funcs(self, arg, _axis):
498
508
raise NotImplementedError ("axis other than 0 is not supported" )
499
509
500
510
if self ._selected_obj .ndim == 1 :
501
- obj = self ._selected_obj
511
+ selected_obj = self ._selected_obj
502
512
else :
503
- obj = self ._obj_with_exclusions
513
+ selected_obj = self ._obj_with_exclusions
504
514
505
515
results = []
506
516
keys = []
507
517
508
518
# degenerate case
509
- if obj .ndim == 1 :
519
+ if selected_obj .ndim == 1 :
510
520
for a in arg :
511
- colg = self ._gotitem (obj .name , ndim = 1 , subset = obj )
521
+ colg = self ._gotitem (selected_obj .name , ndim = 1 , subset = selected_obj )
512
522
try :
513
523
new_res = colg .aggregate (a )
514
524
@@ -523,8 +533,8 @@ def _aggregate_multiple_funcs(self, arg, _axis):
523
533
524
534
# multiples
525
535
else :
526
- for index , col in enumerate (obj ):
527
- colg = self ._gotitem (col , ndim = 1 , subset = obj .iloc [:, index ])
536
+ for index , col in enumerate (selected_obj ):
537
+ colg = self ._gotitem (col , ndim = 1 , subset = selected_obj .iloc [:, index ])
528
538
try :
529
539
new_res = colg .aggregate (arg )
530
540
except (TypeError , DataError ):
0 commit comments