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 3 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 @@ -1130,6 +1130,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
23 changes: 23 additions & 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, column on which to calculate
Expand Down Expand Up @@ -659,6 +660,26 @@ def validate(self):
else:
raise ValueError("Invalid window {0}".format(window))

def _validate_aggregate(self, arg, *args, **kwargs):
# supported weighted window functions
valid_ops = ["mean", "sum"]

def validate_str(op):
if op not in valid_ops:
raise ValueError(
"{op} function is not supported "
"for weighted windows.".format(op=op)
)

if isinstance(arg, str):
validate_str(arg)
elif isinstance(arg, (list, tuple, dict)):
ops = arg.values() if isinstance(arg, dict) else arg

for op in ops:
if isinstance(op, str):
validate_str(op)

def _prep_window(self, **kwargs):
"""
Provide validation for our window type, return the window
Expand Down Expand Up @@ -815,6 +836,8 @@ def f(arg, *args, **kwargs):
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, arg, *args, **kwargs):
self._validate_aggregate(arg)

result, how = self._aggregate(arg, *args, **kwargs)
if result is None:

Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,17 @@ def test_numpy_compat(self, method):
with pytest.raises(UnsupportedFunctionCall, match=msg):
getattr(w, method)(dtype=np.float64)

@pytest.mark.parametrize(
"arg", ["std", ["mean", "std"], ("mean", "std"), {"A": "mean", "B": "std"}]
)
def test_agg_function_support(self, arg):
ser = pd.DataFrame({"A": np.arange(5), "B": np.arange(5)})
roll = ser.rolling(2, win_type="triang")

msg = "std function is not supported for weighted windows."
with pytest.raises(ValueError, match=msg):
roll.agg(arg)


class TestRolling(Base):
def setup_method(self, method):
Expand Down