Skip to content

Commit 53777cd

Browse files
committed
Fix issue, add test
1 parent dc947a4 commit 53777cd

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

doc/source/whatsnew/v2.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,6 +1371,7 @@ Groupby/resample/rolling
13711371
- Bug in :meth:`.DataFrameGroupBy.agg` with ``engine="numba"`` failing to respect ``as_index=False`` (:issue:`51228`)
13721372
- Bug in :meth:`DataFrameGroupBy.agg`, :meth:`SeriesGroupBy.agg`, and :meth:`Resampler.agg` would ignore arguments when passed a list of functions (:issue:`50863`)
13731373
- Bug in :meth:`DataFrameGroupBy.ohlc` ignoring ``as_index=False`` (:issue:`51413`)
1374+
- Bug in :meth:`GroupBy.groups` with a datetime key in conjunction with another key produced incorrect number of group keys (:issue:`51158`)
13741375

13751376
Reshaping
13761377
^^^^^^^^^

pandas/core/groupby/ops.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,6 +1085,9 @@ def groups(self):
10851085
}
10861086
return result
10871087

1088+
def __iter__(self) -> Iterator[Hashable]:
1089+
return iter(self.groupings[0].grouping_vector)
1090+
10881091
@property
10891092
def nkeys(self) -> int:
10901093
# still matches len(self.groupings), but we can hard-code

pandas/tests/groupby/test_grouping.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,29 @@ def test_groupby_grouper_f_sanity_checked(self):
442442
with pytest.raises(AssertionError, match=msg):
443443
ts.groupby(lambda key: key[0:6])
444444

445+
def test_groupby_with_datetime_key(self):
446+
# GH 51158
447+
df = DataFrame(
448+
{
449+
"id": ["a", "b"] * 3,
450+
"b": date_range("2000-01-01", "2000-01-03", freq="9H"),
451+
}
452+
)
453+
grouper = Grouper(key="b", freq="D")
454+
gb = df.groupby([grouper, "id"])
455+
456+
# test number of groups
457+
expected = {
458+
(Timestamp("2000-01-01"), "a"): [0, 2],
459+
(Timestamp("2000-01-01"), "b"): [1],
460+
(Timestamp("2000-01-02"), "a"): [4],
461+
(Timestamp("2000-01-02"), "b"): [3, 5],
462+
}
463+
tm.assert_dict_equal(gb.groups, expected)
464+
465+
# test number of group keys
466+
assert len(gb.groups.keys()) == 4
467+
445468
def test_grouping_error_on_multidim_input(self, df):
446469
msg = "Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional"
447470
with pytest.raises(ValueError, match=msg):

0 commit comments

Comments
 (0)