Skip to content

Commit

Permalink
ENH: support functions passed as strings in groupby.transform just li…
Browse files Browse the repository at this point in the history
…ke aggregate, close #1362
  • Loading branch information
wesm committed Jun 2, 2012
1 parent f62f571 commit 952b272
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
1 change: 1 addition & 0 deletions RELEASE.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ pandas 0.8.0
- Enable Series.asof to work with arrays of timestamp inputs
- Cython implementation of DataFrame.corr speeds up by > 100x (#1349, #1354)
- Exclude "nuisance" columns automatically in GroupBy.transform (#1364)
- Support functions-as-strings in GroupBy.transform (#1362)

**API Changes**

Expand Down
18 changes: 10 additions & 8 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,12 +345,6 @@ def ohlc(self):
"""
return self._cython_agg_general('ohlc')

# def last(self):
# return self.nth(-1)

# def first(self):
# return self.nth(0)

def nth(self, n):
def picker(arr):
if arr is not None:
Expand Down Expand Up @@ -1295,9 +1289,14 @@ def transform(self, func, *args, **kwargs):
"""
result = self.obj.copy()

if isinstance(func, basestring):
wrapper = lambda x: getattr(x, func)(*args, **kwargs)
else:
wrapper = lambda x: func(x, *args, **kwargs)

for name, group in self:
object.__setattr__(group, 'name', name)
res = func(group, *args, **kwargs)
res = wrapper(group)
indexer = self.obj.index.get_indexer(group.index)
np.put(result, indexer, res)

Expand Down Expand Up @@ -1626,7 +1625,10 @@ def transform(self, func, *args, **kwargs):
obj = self._obj_with_exclusions
gen = self.grouper.get_iterator(obj, axis=self.axis)

wrapper = lambda x: func(x, *args, **kwargs)
if isinstance(func, basestring):
wrapper = lambda x: getattr(x, func)(*args, **kwargs)
else:
wrapper = lambda x: func(x, *args, **kwargs)

for name, group in gen:
object.__setattr__(group, 'name', name)
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,15 @@ def test_transform_exclude_nuisance(self):

assert_frame_equal(result, expected)

def test_transform_function_aliases(self):
result = self.df.groupby('A').transform('mean')
expected = self.df.groupby('A').transform(np.mean)
assert_frame_equal(result, expected)

result = self.df.groupby('A')['C'].transform('mean')
expected = self.df.groupby('A')['C'].transform(np.mean)
assert_series_equal(result, expected)

def test_with_na(self):
index = Index(np.arange(10))
values = Series(np.ones(10), index)
Expand Down

0 comments on commit 952b272

Please sign in to comment.