Skip to content

Commit 06cd915

Browse files
committed
Merge pull request #4015 from hayd/GH4104_groupby_index_name
FIX groupby name without multiindex GH4104
2 parents d7fe745 + 5e3cef7 commit 06cd915

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

doc/source/release.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ pandas 0.11.1
214214
names (:issue:`3873`)
215215

216216
- Fixed bug in groupby with empty series referencing a variable before assignment. (:issue:`3510`)
217+
- Allow index name to be used in groupby for non MultiIndex (:issue:`4014`)
217218
- Fixed bug in mixed-frame assignment with aligned series (:issue:`3492`)
218219
- Fixed bug in selecting month/quarter/year from a series would not select the time element
219220
on the last day (:issue:`3546`)

pandas/core/groupby.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,11 +1252,14 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
12521252

12531253
if level is not None:
12541254
if not isinstance(group_axis, MultiIndex):
1255-
if level > 0:
1255+
if isinstance(level, basestring):
1256+
if obj.index.name != level:
1257+
raise ValueError('level name %s is not the name of the index' % level)
1258+
elif level > 0:
12561259
raise ValueError('level > 0 only valid with MultiIndex')
1257-
else:
1258-
level = None
1259-
key = group_axis
1260+
1261+
level = None
1262+
key = group_axis
12601263

12611264
if isinstance(key, CustomGrouper):
12621265
gpr = key.get_grouper(obj)

pandas/tests/test_groupby.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1414,6 +1414,12 @@ def test_groupby_level(self):
14141414
# raise exception for non-MultiIndex
14151415
self.assertRaises(ValueError, self.df.groupby, level=1)
14161416

1417+
def test_groupby_level_index_names(self):
1418+
## GH4014 this used to raise ValueError since 'exp'>1 (in py2)
1419+
df = DataFrame({'exp' : ['A']*3 + ['B']*3, 'var1' : range(6),}).set_index('exp')
1420+
df.groupby(level='exp')
1421+
self.assertRaises(ValueError, df.groupby, level='foo')
1422+
14171423
def test_groupby_level_with_nas(self):
14181424
index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
14191425
labels=[[1, 1, 1, 1, 0, 0, 0, 0],

0 commit comments

Comments
 (0)