Skip to content

Commit 283956e

Browse files
author
suoniq
authored
BUG: Series.groupby fails with InvalidIndexError on time series with … (#42772)
1 parent 13b4ef8 commit 283956e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.3.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Fixed regressions
2626
- Fixed regression in :func:`concat` where ``copy=False`` was not honored in ``axis=1`` Series concatenation (:issue:`42501`)
2727
- Regression in :meth:`Series.nlargest` and :meth:`Series.nsmallest` with nullable integer or float dtype (:issue:`42816`)
2828
- Fixed regression in :meth:`Series.quantile` with :class:`Int64Dtype` (:issue:`42626`)
29+
- 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`)
2930

3031
.. ---------------------------------------------------------------------------
3132

pandas/core/groupby/grouper.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -845,9 +845,11 @@ def is_in_obj(gpr) -> bool:
845845
return False
846846
try:
847847
return gpr is obj[gpr.name]
848-
except (KeyError, IndexError):
848+
except (KeyError, IndexError, InvalidIndexError):
849849
# IndexError reached in e.g. test_skip_group_keys when we pass
850850
# lambda here
851+
# InvalidIndexError raised on key-types inappropriate for index,
852+
# e.g. DatetimeIndex.get_loc(tuple())
851853
return False
852854

853855
for gpr, level in zip(keys, levels):

pandas/tests/groupby/test_grouping.py

+17
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,23 @@ def test_groupby_dict_mapping(self):
400400
tm.assert_series_equal(result, result2)
401401
tm.assert_series_equal(result, expected2)
402402

403+
@pytest.mark.parametrize(
404+
"index",
405+
[
406+
[0, 1, 2, 3],
407+
["a", "b", "c", "d"],
408+
[Timestamp(2021, 7, 28 + i) for i in range(4)],
409+
],
410+
)
411+
def test_groupby_series_named_with_tuple(self, frame_or_series, index):
412+
# GH 42731
413+
obj = frame_or_series([1, 2, 3, 4], index=index)
414+
groups = Series([1, 0, 1, 0], index=index, name=("a", "a"))
415+
result = obj.groupby(groups).last()
416+
expected = frame_or_series([4, 3])
417+
expected.index.name = ("a", "a")
418+
tm.assert_equal(result, expected)
419+
403420
def test_groupby_grouper_f_sanity_checked(self):
404421
dates = date_range("01-Jan-2013", periods=12, freq="MS")
405422
ts = Series(np.random.randn(12), index=dates)

0 commit comments

Comments
 (0)