Skip to content

BUG/FIX: groupby should raise on multi-valued filter #7871

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
Jul 30, 2014
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
3 changes: 2 additions & 1 deletion doc/source/v0.15.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,8 @@ Bug Fixes




- Bug in ``GroupBy.filter()`` where fast path vs. slow path made the filter
return a non scalar value that appeared valid but wasnt' (:issue:`7870`).



Expand Down
42 changes: 14 additions & 28 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2945,48 +2945,34 @@ def filter(self, func, dropna=True, *args, **kwargs):
>>> grouped = df.groupby(lambda x: mapping[x])
>>> grouped.filter(lambda x: x['A'].sum() + x['B'].sum() > 0)
"""
from pandas.tools.merge import concat

indices = []

obj = self._selected_obj
gen = self.grouper.get_iterator(obj, axis=self.axis)

fast_path, slow_path = self._define_paths(func, *args, **kwargs)

path = None
for name, group in gen:
object.__setattr__(group, 'name', name)

if path is None:
# Try slow path and fast path.
try:
path, res = self._choose_path(fast_path, slow_path, group)
except Exception: # pragma: no cover
res = fast_path(group)
path = fast_path
else:
res = path(group)
res = func(group)

def add_indices():
indices.append(self._get_index(name))
try:
res = res.squeeze()
except AttributeError: # allow e.g., scalars and frames to pass
Copy link
Contributor

Choose a reason for hiding this comment

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

yeh, guess this is not necessary for filter

Copy link
Member Author

Choose a reason for hiding this comment

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

the best days are when - outnumbers +

Copy link
Member Author

Choose a reason for hiding this comment

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

sadly this is not the case here :(

Copy link
Contributor

Choose a reason for hiding this comment

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

tests must be counted separately! :)

pass

# interpret the result of the filter
if isinstance(res, (bool, np.bool_)):
if res:
add_indices()
if (isinstance(res, (bool, np.bool_)) or
np.isscalar(res) and isnull(res)):
if res and notnull(res):
indices.append(self._get_index(name))
else:
if getattr(res, 'ndim', None) == 1:
val = res.ravel()[0]
if val and notnull(val):
add_indices()
else:

# in theory you could do .all() on the boolean result ?
raise TypeError("the filter must return a boolean result")
# non scalars aren't allowed
raise TypeError("filter function returned a %s, "
"but expected a scalar bool" %
type(res).__name__)

filtered = self._apply_filter(indices, dropna)
return filtered
return self._apply_filter(indices, dropna)


class DataFrameGroupBy(NDFrameGroupBy):
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3968,6 +3968,32 @@ def test_filter_has_access_to_grouped_cols(self):
filt = g.filter(lambda x: x['A'].sum() == 2)
assert_frame_equal(filt, df.iloc[[0, 1]])

def test_filter_enforces_scalarness(self):
df = pd.DataFrame([
['best', 'a', 'x'],
['worst', 'b', 'y'],
['best', 'c', 'x'],
['best','d', 'y'],
['worst','d', 'y'],
['worst','d', 'y'],
['best','d', 'z'],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('c').filter(lambda g: g['a'] == 'best')

def test_filter_non_bool_raises(self):
df = pd.DataFrame([
['best', 'a', 1],
['worst', 'b', 1],
['best', 'c', 1],
['best','d', 1],
['worst','d', 1],
['worst','d', 1],
['best','d', 1],
], columns=['a', 'b', 'c'])
with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'):
df.groupby('a').filter(lambda g: g.c.mean())

def test_index_label_overlaps_location(self):
# checking we don't have any label/location confusion in the
# the wake of GH5375
Expand Down