From 218ea01ae2debec9d1694e9dc9df0643397958e6 Mon Sep 17 00:00:00 2001 From: eshanj Date: Sun, 11 Dec 2022 17:41:06 -0500 Subject: [PATCH 1/2] BUG/TST Added support for empty dictionary when passed to agg for groupby This adds consistency across empty containers when passed to agg for groupby. Also added new test to check new functionality works as expected. --- pandas/core/apply.py | 18 +++++++++++++----- .../tests/groupby/aggregate/test_aggregate.py | 9 +++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 722de91ba5246..a9a110af857d1 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -413,11 +413,19 @@ def agg_dict_like(self) -> DataFrame | Series: keys_to_use = ktu axis: AxisInt = 0 if isinstance(obj, ABCSeries) else 1 - result = concat( - {k: results[k] for k in keys_to_use}, - axis=axis, - keys=keys_to_use, - ) + + # GH 48581 - Adding consistency to empty agg types + if not results: + # return empty DataFrame if results is empty, following pattern + # empty list and tuple + from pandas import DataFrame + + result = DataFrame() + else: + result = concat( + {k: results[k] for k in keys_to_use}, axis=axis, keys=keys_to_use + ) + elif any(is_ndframe): # There is a mix of NDFrames and scalars raise ValueError( diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 03b917edd357b..63ca85b31bfda 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -1443,3 +1443,12 @@ def test_agg_of_mode_list(test, constant): expected = expected.set_index(0) tm.assert_frame_equal(result, expected) + + +def test_empty_container_consistency(): + df = pd.DataFrame(data={"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + dict_result = df.groupby("a").agg({}) + + expected = DataFrame() + + tm.assert_frame_equal(dict_result, expected) From 2c22e123feb93ddfec7bc22d78781801dc6c9c25 Mon Sep 17 00:00:00 2001 From: eshanj Date: Sun, 11 Dec 2022 18:19:06 -0500 Subject: [PATCH 2/2] Fixed pre-commit error. --- pandas/tests/groupby/aggregate/test_aggregate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 63ca85b31bfda..2d4c50d693133 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -1446,7 +1446,7 @@ def test_agg_of_mode_list(test, constant): def test_empty_container_consistency(): - df = pd.DataFrame(data={"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + df = DataFrame(data={"a": [1, 2], "b": [3, 4], "c": [5, 6]}) dict_result = df.groupby("a").agg({}) expected = DataFrame()