Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Fix Series.groupby raising OutOfBoundsDatetime with DatetimeIndex and month name #54306

Merged
merged 1 commit into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,7 @@ Groupby/resample/rolling
- Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64, timedelta64 or :class:`PeriodDtype` values (:issue:`52128`, :issue:`53045`)
- Bug in :meth:`DataFrameGroupby.resample` with ``kind="period"`` raising ``AttributeError`` (:issue:`24103`)
- Bug in :meth:`Resampler.ohlc` with empty object returning a :class:`Series` instead of empty :class:`DataFrame` (:issue:`42902`)
- Bug in :meth:`Series.groupby` raising an error when grouped :class:`Series` has a :class:`DatetimeIndex` index and a :class:`Series` with a name that is a month is given to the ``by`` argument (:issue:`48509`)
- Bug in :meth:`SeriesGroupBy.count` and :meth:`DataFrameGroupBy.count` where the dtype would be ``np.int64`` for data with :class:`ArrowDtype` or masked dtypes (e.g. ``Int64``) (:issue:`53831`)
- Bug in :meth:`SeriesGroupBy.nth` and :meth:`DataFrameGroupBy.nth` after performing column selection when using ``dropna="any"`` or ``dropna="all"`` would not subset columns (:issue:`53518`)
- Bug in :meth:`SeriesGroupBy.nth` and :meth:`DataFrameGroupBy.nth` raised after performing column selection when using ``dropna="any"`` or ``dropna="all"`` resulted in rows being dropped (:issue:`53518`)
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pandas._config import using_copy_on_write

from pandas._libs import lib
from pandas._libs.tslibs import OutOfBoundsDatetime
from pandas.errors import InvalidIndexError
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
Expand Down Expand Up @@ -969,7 +970,7 @@ def is_in_obj(gpr) -> bool:
# series is part of the object
try:
obj_gpr_column = obj[gpr.name]
except (KeyError, IndexError, InvalidIndexError):
except (KeyError, IndexError, InvalidIndexError, OutOfBoundsDatetime):
return False
if isinstance(gpr, Series) and isinstance(obj_gpr_column, Series):
return gpr._mgr.references_same_values( # type: ignore[union-attr]
Expand All @@ -978,11 +979,13 @@ def is_in_obj(gpr) -> bool:
return False
try:
return gpr is obj[gpr.name]
except (KeyError, IndexError, InvalidIndexError):
Comment on lines 980 to -981
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like any error we hit here will want to be ignored; what are thoughts on just doing try: ... except Exception: return False?

cc @jbrockmendel @mroeschke

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would you get an arbitrary exception here? A couple years back we made a concerted effort to be more specific in what we caught

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there are other issues caused by not being strict enough here e.g. #51818

Copy link
Member

@rhshadrach rhshadrach Jul 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think you can; what I'm thinking is that any exception that can possibly be hit here we want to ignore. I'm not certain that's true though.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the listed exceptions here are ones that make sense if gpr.name is not found in obj.columns. Any other exceptions mean Something Has Gone Wrong and we would want a bug report to be filed

except (KeyError, IndexError, InvalidIndexError, OutOfBoundsDatetime):
# IndexError reached in e.g. test_skip_group_keys when we pass
# lambda here
# InvalidIndexError raised on key-types inappropriate for index,
# e.g. DatetimeIndex.get_loc(tuple())
# OutOfBoundsDatetime raised when obj is a Series with DatetimeIndex
# and gpr.name is month str
return False

for gpr, level in zip(keys, levels):
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3124,3 +3124,12 @@ def test_groupby_with_Time_Grouper():
df = test_data.groupby(Grouper(key="time2", freq="1T")).count().reset_index()

tm.assert_frame_equal(df, expected_output)


def test_groupby_series_with_datetimeindex_month_name():
# GH 48509
s = Series([0, 1, 0], index=date_range("2022-01-01", periods=3), name="jan")
result = s.groupby(s).count()
expected = Series([2, 1], name="jan")
expected.index.name = "jan"
tm.assert_series_equal(result, expected)