Skip to content

Commit

Permalink
BUG: handle grouping aggregations consistently whether as_index is Tr…
Browse files Browse the repository at this point in the history
…ue/False, close #819
  • Loading branch information
adamklein committed Feb 23, 2012
1 parent 2e21a7f commit aca268f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
17 changes: 13 additions & 4 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,10 +1115,19 @@ def aggregate(self, arg, *args, **kwargs):
raise ValueError('Can only pass dict with axis=0')

obj = self._obj_with_exclusions
for col, func in arg.iteritems():
colg = SeriesGroupBy(obj[col], column=col,
grouper=self.grouper)
result[col] = colg.aggregate(func)
# more kludge
if len(obj.columns) == 1:
series_obj = Series(obj.ix[:,0])

This comment has been minimized.

Copy link
@wesm

wesm Feb 24, 2012

Member

What if obj has integer columns?

This comment has been minimized.

Copy link
@adamklein

adamklein Feb 24, 2012

Author Contributor

Um, right. Good call.

series_name = obj.columns[0]
for col, func in arg.iteritems():
colg = SeriesGroupBy(series_obj, column=series_name,
grouper=self.grouper)
result[col] = colg.aggregate(func)
else:
for col, func in arg.iteritems():
colg = SeriesGroupBy(obj[col], column=col,
grouper=self.grouper)
result[col] = colg.aggregate(func)

result = DataFrame(result)
elif isinstance(arg, list):
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,12 @@ def test_groupby_as_index_agg(self):
expected2['D'] = grouped.sum()['D']
assert_frame_equal(result2, expected2)

grouped = self.df.groupby('A', as_index=True)
expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C' : 'Q'})
result3 = grouped['C'].agg({'Q' : np.sum})
assert_frame_equal(result3, expected3)

# multi-key

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

expected3 = grouped['C'].sum()
expected3 = DataFrame(expected3).rename(columns={'C' : 'Q'})
result3 = grouped['C'].agg({'Q' : np.sum})
assert_frame_equal(result3, expected3)


def test_as_index_series_return_frame(self):
grouped = self.df.groupby('A', as_index=False)
grouped2 = self.df.groupby(['A', 'B'], as_index=False)
Expand Down

0 comments on commit aca268f

Please sign in to comment.