diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 6fa5ce0a201ae..d241132e4d960 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -430,16 +430,23 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): result = grouped._aggregate_item_by_item(how, *args, **kwargs) else: result = grouped.aggregate(how, *args, **kwargs) - except (DataError, AttributeError, KeyError): + except DataError: + # got TypeErrors on aggregation + result = grouped.apply(how, *args, **kwargs) + except (AttributeError, KeyError): # we have a non-reducing function; try to evaluate # alternatively we want to evaluate only a column of the input + + # test_apply_to_one_column_of_df the function being applied references + # a DataFrame column, but aggregate_item_by_item operates column-wise + # on Series, raising AttributeError or KeyError + # (depending on whether the column lookup uses getattr/__getitem__) result = grouped.apply(how, *args, **kwargs) + except ValueError as err: if "Must produce aggregated value" in str(err): # raised in _aggregate_named - pass - elif "len(index) != len(labels)" in str(err): - # raised in libgroupby validation + # see test_apply_without_aggregation, test_apply_with_mutated_index pass else: raise diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index 999d8a6c90ba2..f5fc1888d611c 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -354,11 +354,15 @@ def test_apply_to_one_column_of_df(): {"col": range(10), "col1": range(10, 20)}, index=date_range("2012-01-01", periods=10, freq="20min"), ) + + # access "col" via getattr -> make sure we handle AttributeError result = df.resample("H").apply(lambda group: group.col.sum()) expected = Series( [3, 12, 21, 9], index=date_range("2012-01-01", periods=4, freq="H") ) tm.assert_series_equal(result, expected) + + # access "col" via _getitem__ -> make sure we handle KeyErrpr result = df.resample("H").apply(lambda group: group["col"].sum()) tm.assert_series_equal(result, expected)