Skip to content

BUG: transform and filter misbehave when grouping on categorical data #9994

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.16.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -247,3 +247,5 @@ Bug Fixes


- Bug in hiding ticklabels with subplots and shared axes when adding a new plot to an existing grid of axes (:issue:`9158`)
- Bug in ``transform`` and ``filter`` when grouping on a categorical variable (:issue:`9921`)
- Bug in ``transform`` when groups are equal in number and dtype to the input index (:issue:`9700`)
53 changes: 27 additions & 26 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
notnull, _DATELIKE_DTYPES, is_numeric_dtype,
is_timedelta64_dtype, is_datetime64_dtype,
is_categorical_dtype, _values_from_object,
is_datetime_or_timedelta_dtype, is_bool_dtype,
AbstractMethodError)
is_datetime_or_timedelta_dtype, is_bool,
is_bool_dtype, AbstractMethodError)
from pandas.core.config import option_context
import pandas.lib as lib
from pandas.lib import Timestamp
Expand Down Expand Up @@ -491,7 +491,7 @@ def _set_result_index_ordered(self, result):

# shortcut of we have an already ordered grouper
if not self.grouper.is_monotonic:
index = Index(np.concatenate([ indices[v] for v in self.grouper.result_index ]))
index = Index(np.concatenate([ indices.get(v, []) for v in self.grouper.result_index]))
result.index = index
result = result.sort_index()

Expand Down Expand Up @@ -2436,6 +2436,8 @@ def transform(self, func, *args, **kwargs):

wrapper = lambda x: func(x, *args, **kwargs)
for i, (name, group) in enumerate(self):
if name not in self.indices:
continue

object.__setattr__(group, 'name', name)
res = wrapper(group)
Expand All @@ -2451,7 +2453,7 @@ def transform(self, func, *args, **kwargs):
except:
pass

indexer = self._get_index(name)
indexer = self.indices[name]
result[indexer] = res

result = _possibly_downcast_to_dtype(result, dtype)
Expand All @@ -2465,9 +2467,12 @@ def _transform_fast(self, func):
"""
if isinstance(func, compat.string_types):
func = getattr(self,func)

values = func().values
counts = self.size().values
counts = self.size().fillna(0).values
values = np.repeat(values, com._ensure_platform_int(counts))
if any(counts == 0):
values = self._try_cast(values, self._selected_obj)

return self._set_result_index_ordered(Series(values))

Expand Down Expand Up @@ -2502,8 +2507,11 @@ def true_and_notnull(x, *args, **kwargs):
return b and notnull(b)

try:
indices = [self._get_index(name) if true_and_notnull(group) else []
for name, group in self]
indices = []
for name, group in self:
if true_and_notnull(group) and name in self.indices:
indices.append(self.indices[name])

except ValueError:
raise TypeError("the filter must return a boolean result")
except TypeError:
Expand Down Expand Up @@ -3020,24 +3028,18 @@ def transform(self, func, *args, **kwargs):
if not result.columns.equals(obj.columns):
return self._transform_general(func, *args, **kwargs)

# a grouped that doesn't preserve the index, remap index based on the grouper
# and broadcast it
if ((not isinstance(obj.index,MultiIndex) and
type(result.index) != type(obj.index)) or
len(result.index) != len(obj.index)):
results = np.empty_like(obj.values, result.values.dtype)
indices = self.indices
for (name, group), (i, row) in zip(self, result.iterrows()):
results = np.empty_like(obj.values, result.values.dtype)
indices = self.indices
for (name, group), (i, row) in zip(self, result.iterrows()):
if name in indices:
indexer = indices[name]
results[indexer] = np.tile(row.values,len(indexer)).reshape(len(indexer),-1)
return DataFrame(results,columns=result.columns,index=obj.index).convert_objects()

# we can merge the result in
# GH 7383
names = result.columns
result = obj.merge(result, how='outer', left_index=True, right_index=True).iloc[:,-result.shape[1]:]
result.columns = names
return result
counts = self.size().fillna(0).values
if any(counts == 0):
results = self._try_cast(results, obj[result.columns])
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section was almost unreachable (see the conditions above). In fact, it's no longer reached by test case that motivated it. And it's still not locked down enough: it can only work correctly when the initial groupby was on the index, which transform doesn't know. I have an idea on how to make something like this work in the general case, but I'll wait until this PR goes through.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably ; pls run a perf test to validate

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is about a 25% slowdown in some cases:

-------------------------------------------------------------------------------
Test name                                    | head[ms] | base[ms] |  ratio   |
-------------------------------------------------------------------------------
groupby_transform_series2                    | 124.4840 | 124.6049 |   0.9990 |
groupby_transform                            | 152.5413 | 151.6960 |   1.0056 |
groupby_transform_series                     |  20.0484 |  19.6927 |   1.0181 |
groupby_transform_ufunc                      | 112.1867 | 110.1057 |   1.0189 |
groupby_transform_multi_key4                 | 156.6887 | 138.9330 |   1.1278 |
groupby_transform_multi_key3                 | 918.0430 | 758.8653 |   1.2098 |
groupby_transform_multi_key2                 |  57.8043 |  46.5036 |   1.2430 |
groupby_transform_multi_key1                 |  87.1673 |  69.4257 |   1.2555 |

but that's because of the rest of the change, not this particular piece. (Because anything with a MultiIndex already takes the slow path). The groupby_transform_ufunc test is the relevant one, and there's no change there.

This piece of the change also fixes GH #9700. I'll add a test for that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok if u can profile and see if u can fix would be gr8


return DataFrame(results,columns=result.columns,index=obj.index).convert_objects()

def _define_paths(self, func, *args, **kwargs):
if isinstance(func, compat.string_types):
Expand Down Expand Up @@ -3129,10 +3131,9 @@ def filter(self, func, dropna=True, *args, **kwargs):
pass

# interpret the result of the filter
if (isinstance(res, (bool, np.bool_)) or
np.isscalar(res) and isnull(res)):
if res and notnull(res):
indices.append(self._get_index(name))
if is_bool(res) or (lib.isscalar(res) and isnull(res)):
if res and notnull(res) and name in self.indices:
indices.append(self.indices[name])
else:
# non scalars aren't allowed
raise TypeError("filter function returned a %s, "
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1820,6 +1820,27 @@ def f(x):
expected['person_name'] = expected['person_name'].astype('object')
tm.assert_frame_equal(result, expected)

# GH 9921
# Monotonic
df = DataFrame({"a": [5, 15, 25]})
c = pd.cut(df.a, bins=[0,10,20,30,40])
tm.assert_series_equal(df.a.groupby(c).transform(sum), df['a'])
tm.assert_series_equal(df.a.groupby(c).transform(lambda xs: np.sum(xs)), df['a'])
tm.assert_frame_equal(df.groupby(c).transform(sum), df[['a']])
tm.assert_frame_equal(df.groupby(c).transform(lambda xs: np.max(xs)), df[['a']])

# Filter
tm.assert_series_equal(df.a.groupby(c).filter(np.all), df['a'])
tm.assert_frame_equal(df.groupby(c).filter(np.all), df)

# Non-monotonic
df = DataFrame({"a": [5, 15, 25, -5]})
c = pd.cut(df.a, bins=[-10, 0,10,20,30,40])
tm.assert_series_equal(df.a.groupby(c).transform(sum), df['a'])
tm.assert_series_equal(df.a.groupby(c).transform(lambda xs: np.sum(xs)), df['a'])
tm.assert_frame_equal(df.groupby(c).transform(sum), df[['a']])
tm.assert_frame_equal(df.groupby(c).transform(lambda xs: np.sum(xs)), df[['a']])

def test_pivot_table(self):

raw_cat1 = Categorical(["a","a","b","b"], categories=["a","b","z"], ordered=True)
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,12 @@ def demean(arr):
g = df.groupby(pd.TimeGrouper('M'))
g.transform(lambda x: x-1)

# GH 9700
df = DataFrame({'a' : range(5, 10), 'b' : range(5)})
result = df.groupby('a').transform(max)
expected = DataFrame({'b' : range(5)})
tm.assert_frame_equal(result, expected)

def test_transform_fast(self):

df = DataFrame( { 'id' : np.arange( 100000 ) / 3,
Expand Down