Skip to content

BUG: fix groupby with tuple bug #8123

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 1 commit into from
Aug 28, 2014
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion doc/source/v0.15.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,7 @@ Bug Fixes




- Bug in accessing groups from a ``GroupBy`` when the original grouper
was a tuple (:issue:`8121`).


13 changes: 11 additions & 2 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,9 +431,18 @@ def convert(key, s):
sample = next(iter(self.indices))
if isinstance(sample, tuple):
if not isinstance(name, tuple):
raise ValueError("must supply a tuple to get_group with multiple grouping keys")
msg = ("must supply a tuple to get_group with multiple"
" grouping keys")
raise ValueError(msg)
if not len(name) == len(sample):
raise ValueError("must supply a a same-length tuple to get_group with multiple grouping keys")
try:
# If the original grouper was a tuple
return self.indices[name]
except KeyError:
# turns out it wasn't a tuple
msg = ("must supply a a same-length tuple to get_group"
" with multiple grouping keys")
raise ValueError(msg)

name = tuple([ convert(n, k) for n, k in zip(name,sample) ])

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,23 @@ def test_get_group(self):
self.assertRaises(ValueError, lambda : g.get_group(('foo')))
self.assertRaises(ValueError, lambda : g.get_group(('foo','bar','baz')))

def test_get_group_grouped_by_tuple(self):
# GH 8121
df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]],
index=['ids']).T
gr = df.groupby('ids')
expected = DataFrame({'ids': [(1,), (1,)]}, index=[0, 2])
result = gr.get_group((1,))
assert_frame_equal(result, expected)

dt = pd.to_datetime(['2010-01-01', '2010-01-02', '2010-01-01',
'2010-01-02'])
df = DataFrame({'ids': [(x,) for x in dt]})
gr = df.groupby('ids')
result = gr.get_group(('2010-01-01',))
expected = DataFrame({'ids': [(dt[0],), (dt[0],)]}, index=[0, 2])
assert_frame_equal(result, expected)

def test_agg_apply_corner(self):
# nothing to group, all NA
grouped = self.ts.groupby(self.ts * np.nan)
Expand Down