@@ -420,8 +420,10 @@ def agg_dict_like(self) -> DataFrame | Series:
420
420
if selected_obj .ndim == 1 :
421
421
# key only used for output
422
422
colg = obj ._gotitem (selection , ndim = 1 )
423
- results = {key : colg .agg (how ) for key , how in arg .items ()}
423
+ result_data = [colg .agg (how ) for _ , how in arg .items ()]
424
+ result_index = list (arg .keys ())
424
425
elif is_non_unique_col :
426
+ # key used for column selection and output
425
427
# GH#51099
426
428
result_data = []
427
429
result_index = []
@@ -432,32 +434,31 @@ def agg_dict_like(self) -> DataFrame | Series:
432
434
for index , label in zip (indices , labels ):
433
435
label_to_indices [label ].append (index )
434
436
435
- for indices in label_to_indices .values ():
436
- for indice in indices :
437
- result_index .append (key )
438
- result_data .append (
439
- selected_obj ._ixs (indice , axis = 1 ).agg (how )
440
- )
437
+ key_data = [
438
+ selected_obj ._ixs (indice , axis = 1 ).agg (how )
439
+ for label , indices in label_to_indices .items ()
440
+ for indice in indices
441
+ ]
442
+
443
+ result_index += [key ] * len (key_data )
444
+ result_data += key_data
441
445
else :
442
446
# key used for column selection and output
443
- results = {
444
- key : obj ._gotitem (key , ndim = 1 ).agg (how ) for key , how in arg .items ()
445
- }
446
- # set the final keys
447
- keys = list (arg .keys ())
447
+ result_data = [
448
+ obj ._gotitem (key , ndim = 1 ).agg (how ) for key , how in arg .items ()
449
+ ]
450
+ result_index = list (arg .keys ())
448
451
449
452
# Avoid making two isinstance calls in all and any below
450
- if is_non_unique_col :
451
- is_ndframe = [False ]
452
- else :
453
- is_ndframe = [isinstance (r , ABCNDFrame ) for r in results .values ()]
453
+ is_ndframe = [isinstance (r , ABCNDFrame ) for r in result_data ]
454
454
455
455
# combine results
456
456
if all (is_ndframe ):
457
+ results = dict (zip (result_index , result_data ))
457
458
keys_to_use : Iterable [Hashable ]
458
- keys_to_use = [k for k in keys if not results [k ].empty ]
459
+ keys_to_use = [k for k in result_index if not results [k ].empty ]
459
460
# Have to check, if at least one DataFrame is not empty.
460
- keys_to_use = keys_to_use if keys_to_use != [] else keys
461
+ keys_to_use = keys_to_use if keys_to_use != [] else result_index
461
462
if selected_obj .ndim == 2 :
462
463
# keys are columns, so we can preserve names
463
464
ktu = Index (keys_to_use )
@@ -488,10 +489,7 @@ def agg_dict_like(self) -> DataFrame | Series:
488
489
else :
489
490
name = None
490
491
491
- if is_non_unique_col :
492
- result = Series (result_data , index = result_index , name = name )
493
- else :
494
- result = Series (results , name = name )
492
+ result = Series (result_data , index = result_index , name = name )
495
493
496
494
return result
497
495
0 commit comments