Skip to content

ENH: Raise ValueError for unsupported Window functions #27275

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 18 commits into from
Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from 15 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,7 @@ Groupby/resample/rolling
- Bug in :meth:`pandas.core.window.Rolling.median` and :meth:`pandas.core.window.Rolling.quantile` where incorrect results are returned with ``closed='left'`` and ``closed='neither'`` (:issue:`26005`)
- Improved :class:`pandas.core.window.Rolling`, :class:`pandas.core.window.Window` and :class:`pandas.core.window.EWM` functions to exclude nuisance columns from results instead of raising errors and raise a ``DataError`` only if all columns are nuisance (:issue:`12537`)
- Bug in :meth:`pandas.core.window.Rolling.max` and :meth:`pandas.core.window.Rolling.min` where incorrect results are returned with an empty variable window (:issue:`26005`)
- Raise a helpful exception when an unsupported weighted window function is used as an argument of :meth:`pandas.core.window.Window.aggregate` (:issue:`26597`)

Reshaping
^^^^^^^^^
Expand Down
12 changes: 10 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,16 @@ def _try_aggregate_string_function(self, arg, *args, **kwargs):

f = getattr(np, arg, None)
if f is not None:
return f(self, *args, **kwargs)
try:
return f(self, *args, **kwargs)

except (AttributeError, TypeError):
raise AttributeError(
Copy link
Contributor

Choose a reason for hiding this comment

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

I would pass here, then just use a single raise (line 326)

"'{arg}' is not a valid function for "
"'{cls}' object".format(arg=arg, cls=type(self).__name__)
)

raise ValueError("{arg} is an unknown string function".format(arg=arg))
raise AttributeError("'{arg}' is an unknown string function".format(arg=arg))

def _aggregate(self, arg, *args, **kwargs):
"""
Expand Down Expand Up @@ -555,6 +562,7 @@ def is_any_frame():
elif is_list_like(arg):
# we require a list, but not an 'str'
return self._aggregate_multiple_funcs(arg, _level=_level, _axis=_axis), None

else:
result = None

Expand Down
1 change: 1 addition & 0 deletions pandas/core/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@ class Window(_Window):
Set the labels at the center of the window.
win_type : str, default None
Provide a window type. If ``None``, all points are evenly weighted.
Other types are only applicable for `mean` and `sum` functions.
Copy link
Contributor

Choose a reason for hiding this comment

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

this should be on .agg so I wouldn't add anything here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

agg is using shared_docs. I was avoiding to copy it and make a single line change. Will remove it only if no objection

See the notes below for further information.
on : str, optional
For a DataFrame, a datetime-like column on which to calculate the rolling
Expand Down
30 changes: 30 additions & 0 deletions pandas/tests/window/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,22 @@ def test_numpy_compat(self, method):
with pytest.raises(UnsupportedFunctionCall, match=msg):
getattr(w, method)(dtype=np.float64)

@td.skip_if_no_scipy
@pytest.mark.parametrize("arg", ["median", "var", "std"])
def test_agg_function_support(self, arg):
df = pd.DataFrame({"A": np.arange(5)})
roll = df.rolling(2, win_type="triang")

msg = "'{arg}' is not a valid function for " "'Window' object".format(arg=arg)
with pytest.raises(AttributeError, match=msg):
roll.agg(arg)

with pytest.raises(AttributeError, match=msg):
roll.agg([arg])

with pytest.raises(AttributeError, match=msg):
roll.agg({"A": arg})


class TestRolling(Base):
def setup_method(self, method):
Expand Down Expand Up @@ -921,6 +937,20 @@ def test_numpy_compat(self, method):
with pytest.raises(UnsupportedFunctionCall, match=msg):
getattr(e, method)(dtype=np.float64)

def test_agg_unknown(self):
df = pd.DataFrame({"A": np.arange(5)})
roll = df.rolling(2)

msg = "'foo' is an unknown string function"
with pytest.raises(AttributeError, match=msg):
roll.agg("foo")

with pytest.raises(AttributeError, match=msg):
roll.agg(["foo"])

with pytest.raises(AttributeError, match=msg):
roll.agg({"A": "foo"})


@pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
class TestMoments(Base):
Expand Down