Skip to content

Commit aca268f

Browse files
committed
BUG: handle grouping aggregations consistently whether as_index is True/False, close #819
1 parent 2e21a7f commit aca268f

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

pandas/core/groupby.py

+13-4
Original file line numberDiff line numberDiff line change
@@ -1115,10 +1115,19 @@ def aggregate(self, arg, *args, **kwargs):
11151115
raise ValueError('Can only pass dict with axis=0')
11161116

11171117
obj = self._obj_with_exclusions
1118-
for col, func in arg.iteritems():
1119-
colg = SeriesGroupBy(obj[col], column=col,
1120-
grouper=self.grouper)
1121-
result[col] = colg.aggregate(func)
1118+
# more kludge
1119+
if len(obj.columns) == 1:
1120+
series_obj = Series(obj.ix[:,0])
1121+
series_name = obj.columns[0]
1122+
for col, func in arg.iteritems():
1123+
colg = SeriesGroupBy(series_obj, column=series_name,
1124+
grouper=self.grouper)
1125+
result[col] = colg.aggregate(func)
1126+
else:
1127+
for col, func in arg.iteritems():
1128+
colg = SeriesGroupBy(obj[col], column=col,
1129+
grouper=self.grouper)
1130+
result[col] = colg.aggregate(func)
11221131

11231132
result = DataFrame(result)
11241133
elif isinstance(arg, list):

pandas/tests/test_groupby.py

+12
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,12 @@ def test_groupby_as_index_agg(self):
686686
expected2['D'] = grouped.sum()['D']
687687
assert_frame_equal(result2, expected2)
688688

689+
grouped = self.df.groupby('A', as_index=True)
690+
expected3 = grouped['C'].sum()
691+
expected3 = DataFrame(expected3).rename(columns={'C' : 'Q'})
692+
result3 = grouped['C'].agg({'Q' : np.sum})
693+
assert_frame_equal(result3, expected3)
694+
689695
# multi-key
690696

691697
grouped = self.df.groupby(['A', 'B'], as_index=False)
@@ -699,6 +705,12 @@ def test_groupby_as_index_agg(self):
699705
expected2['D'] = grouped.sum()['D']
700706
assert_frame_equal(result2, expected2)
701707

708+
expected3 = grouped['C'].sum()
709+
expected3 = DataFrame(expected3).rename(columns={'C' : 'Q'})
710+
result3 = grouped['C'].agg({'Q' : np.sum})
711+
assert_frame_equal(result3, expected3)
712+
713+
702714
def test_as_index_series_return_frame(self):
703715
grouped = self.df.groupby('A', as_index=False)
704716
grouped2 = self.df.groupby(['A', 'B'], as_index=False)

0 commit comments

Comments
 (0)