Skip to content

ERR: Raise NotImplementedError with BaseIndexer and certain rolling operations #33057

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 9 commits into from
Mar 29, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ Other API changes
- Added :meth:`DataFrame.value_counts` (:issue:`5377`)
- :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`)
- ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`)
- Using a :func:`pandas.api.indexers.BaseIndexer` with ``min``, ``max``, ``std``, ``var``, ``count``, ``skew``, ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`)
-

Backwards incompatible API changes
Expand Down
10 changes: 10 additions & 0 deletions pandas/core/window/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,13 @@ def func(arg, window, min_periods=None):
return cfunc(arg, window, min_periods)

return func


def validate_baseindexer_support(func_name: Optional[str]) -> None:
# GH 32865: These functions work correctly with a BaseIndexer subclass
BASEINDEXER_WHITELIST = {"mean", "sum", "median", "kurt", "quantile"}
if isinstance(func_name, str) and func_name not in BASEINDEXER_WHITELIST:
raise NotImplementedError(
f"{func_name} is not supported with using a BaseIndexer "
f"subclasses. You can use .apply() with {func_name}."
)
14 changes: 12 additions & 2 deletions pandas/core/window/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
calculate_center_offset,
calculate_min_periods,
get_weighted_roll_func,
validate_baseindexer_support,
zsqrt,
)
from pandas.core.window.indexers import (
Expand Down Expand Up @@ -391,11 +392,12 @@ def _get_cython_func_type(self, func: str) -> Callable:
return self._get_roll_func(f"{func}_variable")
return partial(self._get_roll_func(f"{func}_fixed"), win=self._get_window())

def _get_window_indexer(self, window: int) -> BaseIndexer:
def _get_window_indexer(self, window: int, func_name: Optional[str]) -> BaseIndexer:
"""
Return an indexer class that will compute the window start and end bounds
"""
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support(func_name)
return self.window
if self.is_freq_type:
return VariableWindowIndexer(index_array=self._on.asi8, window_size=window)
Expand Down Expand Up @@ -441,7 +443,7 @@ def _apply(

blocks, obj = self._create_blocks()
block_list = list(blocks)
window_indexer = self._get_window_indexer(window)
window_indexer = self._get_window_indexer(window, name)

results = []
exclude: List[Scalar] = []
Expand Down Expand Up @@ -1173,6 +1175,8 @@ class _Rolling_and_Expanding(_Rolling):
)

def count(self):
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support("count")

blocks, obj = self._create_blocks()
results = []
Expand Down Expand Up @@ -1627,6 +1631,9 @@ def quantile(self, quantile, interpolation="linear", **kwargs):
"""

def cov(self, other=None, pairwise=None, ddof=1, **kwargs):
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support("cov")

if other is None:
other = self._selected_obj
# only default unset
Expand Down Expand Up @@ -1770,6 +1777,9 @@ def _get_cov(X, Y):
)

def corr(self, other=None, pairwise=None, **kwargs):
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support("corr")

if other is None:
other = self._selected_obj
# only default unset
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/window/test_base_indexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,18 @@ def get_window_bounds(self, num_values, min_periods, center, closed):
indexer = CustomIndexer()
with pytest.raises(NotImplementedError, match="BaseIndexer subclasses not"):
df.rolling(indexer, win_type="boxcar")


@pytest.mark.parametrize(
"func", ["min", "max", "std", "var", "count", "skew", "cov", "corr"]
)
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer):
def get_window_bounds(self, num_values, min_periods, center, closed):
return np.array([0, 1]), np.array([1, 2])

df = DataFrame({"values": range(2)})
indexer = CustomIndexer()
with pytest.raises(NotImplementedError, match=f"{func} is not supported"):
getattr(df.rolling(indexer), func)()