Skip to content

Commit

Permalink
CLN: no need to catch libgroupby validation ValueError (#41240)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel committed Apr 30, 2021
1 parent 4d604fb commit f33480d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 11 additions & 4 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/resample/test_resampler_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit f33480d

Please sign in to comment.