Skip to content

Commit 6bd2900

Browse files
suoniqmeeseeksmachine
suoniq
authored andcommitted
Backport PR pandas-dev#42772: BUG: Series.groupby fails with InvalidIndexError on time series with …
1 parent 6c58fa8 commit 6bd2900

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
@@ -833,9 +833,11 @@ def is_in_obj(gpr) -> bool:
833833
return False
834834
try:
835835
return gpr is obj[gpr.name]
836-
except (KeyError, IndexError):
836+
except (KeyError, IndexError, InvalidIndexError):
837837
# IndexError reached in e.g. test_skip_group_keys when we pass
838838
# lambda here
839+
# InvalidIndexError raised on key-types inappropriate for index,
840+
# e.g. DatetimeIndex.get_loc(tuple())
839841
return False
840842

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

pandas/tests/groupby/test_grouping.py

+17
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,23 @@ def test_groupby_dict_mapping(self):
396396
tm.assert_series_equal(result, result2)
397397
tm.assert_series_equal(result, expected2)
398398

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

0 commit comments

Comments
 (0)