Skip to content

Commit 92e5c50

Browse files
committed
BUG: bug in head/tail of groupby for returning selected columns (GH6524)
1 parent 30d3cba commit 92e5c50

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

pandas/core/groupby.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,8 @@ def head(self, n=5):
607607
"""
608608
rng = np.arange(self.grouper._max_groupsize, dtype='int64')
609609
in_head = self._cumcount_array(rng) < n
610-
head = self.obj[in_head]
610+
obj = self._obj_with_exclusions
611+
head = obj.iloc[in_head]
611612
if self.as_index:
612613
head.index = self._index_with_as_index(in_head)
613614
return head
@@ -636,7 +637,8 @@ def tail(self, n=5):
636637
"""
637638
rng = np.arange(0, -self.grouper._max_groupsize, -1, dtype='int64')
638639
in_tail = self._cumcount_array(rng, ascending=False) > -n
639-
tail = self.obj[in_tail]
640+
obj = self._obj_with_exclusions
641+
tail = obj.iloc[in_tail]
640642
if self.as_index:
641643
tail.index = self._index_with_as_index(in_tail)
642644
return tail

pandas/tests/test_groupby.py

+16
Original file line numberDiff line numberDiff line change
@@ -2455,6 +2455,22 @@ def test_getitem_list_of_columns(self):
24552455
assert_frame_equal(result2, expected)
24562456
assert_frame_equal(result3, expected)
24572457

2458+
def test_validate_getitem(self):
2459+
2460+
# invalid getitems
2461+
# GH 6524
2462+
df = DataFrame({"Dummy":[1,2]*6,
2463+
"X":[1,3,7]*4,
2464+
"Y":[2,3,4]*4,
2465+
"group":["A","B"]*6})
2466+
expected = DataFrame({"X":[1,3],
2467+
"Y":[2,3]},
2468+
index = MultiIndex.from_tuples([('A',0),('B',1)],names=['group',None]))
2469+
result = df.groupby('group')[['X', 'Y']].head(1)
2470+
assert_frame_equal(result, expected)
2471+
2472+
self.assertRaises(AttributeError, lambda : df.groupby('group').loc[:,['X', 'Y']].head(1))
2473+
24582474
def test_agg_multiple_functions_maintain_order(self):
24592475
# GH #610
24602476
funcs = [('mean', np.mean), ('max', np.max), ('min', np.min)]

0 commit comments

Comments
 (0)