Skip to content

Commit 8ac1eab

Browse files
committed
Merge pull request #11202 from rinoc/GH11185
BUG: groupby list of keys with same length as index
2 parents 2f59a02 + 1c60e6a commit 8ac1eab

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v0.17.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1186,3 +1186,4 @@ Bug Fixes
11861186
- Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`)
11871187
- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`)
11881188
- Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`)
1189+
- Bug in ``.groupby`` when number of keys to group by is same as length of index (:issue:`11185`)

pandas/core/groupby.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2111,6 +2111,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
21112111
# what are we after, exactly?
21122112
match_axis_length = len(keys) == len(group_axis)
21132113
any_callable = any(callable(g) or isinstance(g, dict) for g in keys)
2114+
any_groupers = any(isinstance(g, Grouper) for g in keys)
21142115
any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray))
21152116
for g in keys)
21162117

@@ -2123,7 +2124,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
21232124
all_in_columns = False
21242125

21252126
if (not any_callable and not all_in_columns
2126-
and not any_arraylike and match_axis_length
2127+
and not any_arraylike and not any_groupers
2128+
and match_axis_length
21272129
and level is None):
21282130
keys = [com._asarray_tuplesafe(keys)]
21292131

pandas/tests/test_groupby.py

+12
Original file line numberDiff line numberDiff line change
@@ -2989,6 +2989,18 @@ def test_groupby_list_infer_array_like(self):
29892989
result = df.groupby(['foo', 'bar']).mean()
29902990
expected = df.groupby([df['foo'], df['bar']]).mean()[['val']]
29912991

2992+
def test_groupby_keys_same_size_as_index(self):
2993+
# GH 11185
2994+
freq = 's'
2995+
index = pd.date_range(start=np.datetime64(
2996+
'2015-09-29T11:34:44-0700'), periods=2, freq=freq)
2997+
df = pd.DataFrame([['A', 10], ['B', 15]], columns=[
2998+
'metric', 'values'], index=index)
2999+
result = df.groupby([pd.Grouper(level=0, freq=freq), 'metric']).mean()
3000+
expected = df.set_index([df.index, 'metric'])
3001+
3002+
assert_frame_equal(result, expected)
3003+
29923004
def test_groupby_nat_exclude(self):
29933005
# GH 6992
29943006
df = pd.DataFrame({'values': np.random.randn(8),

0 commit comments

Comments
 (0)