Skip to content

BUG: Series.groupby fails with InvalidIndexError on time series with … #42772

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

Merged
merged 5 commits into from Sep 6, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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/v1.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Fixed regressions
- Fixed regression in :func:`concat` where ``copy=False`` was not honored in ``axis=1`` Series concatenation (:issue:`42501`)
- Regression in :meth:`Series.nlargest` and :meth:`Series.nsmallest` with nullable integer or float dtype (:issue:`42816`)
- Fixed regression in :meth:`Series.quantile` with :class:`Int64Dtype` (:issue:`42626`)
- Fixed regression in :meth:`Series.groupby` and :meth:`DataFrame.groupby` where supplying the ``by`` argument with a Series named with a tuple would incorrectly raise (:issue:`42731`)

.. ---------------------------------------------------------------------------

Expand Down
4 changes: 3 additions & 1 deletion pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,9 +845,11 @@ def is_in_obj(gpr) -> bool:
return False
try:
return gpr is obj[gpr.name]
except (KeyError, IndexError):
except (KeyError, IndexError, InvalidIndexError):
# 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())
return False

for gpr, level in zip(keys, levels):
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,24 @@ def test_groupby_dict_mapping(self):
tm.assert_series_equal(result, result2)
tm.assert_series_equal(result, expected2)

@pytest.mark.parametrize(
"index",
[
[0, 1, 2, 3],
["a", "b", "c", "d"],
[Timestamp(2021, 7, 28 + i) for i in range(4)],
],
)
@pytest.mark.parametrize("box", [Series, DataFrame])
def test_groupby_series_named_with_tuple(self, box, index):
# GH 42731
obj = box([1, 2, 3, 4], index=index)
groups = Series([1, 0, 1, 0], index=index, name=("a", "a"))
result = obj.groupby(groups).last()
expected = box([4, 3])
expected.index.name = ("a", "a")
tm.assert_equal(result, expected)

def test_groupby_grouper_f_sanity_checked(self):
dates = date_range("01-Jan-2013", periods=12, freq="MS")
ts = Series(np.random.randn(12), index=dates)
Expand Down