Skip to content
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

Deprecate center on df.expanding #34887

Merged
merged 4 commits into from
Jul 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 3 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,9 @@ Deprecations
precision through the ``rtol``, and ``atol`` parameters, thus deprecating the
``check_less_precise`` parameter. (:issue:`13357`).
- :func:`DataFrame.melt` accepting a value_name that already exists is deprecated, and will be removed in a future version (:issue:`34731`)
- the ``center`` keyword in the :meth:`DataFrame.expanding` function is deprecated and will be removed in a future version (:issue:`20647`)
MBrouns marked this conversation as resolved.
Show resolved Hide resolved



.. ---------------------------------------------------------------------------

Expand Down
18 changes: 12 additions & 6 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import builtins
import textwrap
from typing import Any, Dict, FrozenSet, List, Optional, Union
import warnings

import numpy as np

Expand Down Expand Up @@ -581,12 +582,17 @@ def _shallow_copy(self, obj, **kwargs):
"""
return a new object with the replacement attributes
"""
if isinstance(obj, self._constructor):
obj = obj.obj
for attr in self._attributes:
if attr not in kwargs:
kwargs[attr] = getattr(self, attr)
return self._constructor(obj, **kwargs)
with warnings.catch_warnings():
MBrouns marked this conversation as resolved.
Show resolved Hide resolved
warnings.filterwarnings(
"ignore",
"The `center` argument on `expanding` will be removed in the future",
)
if isinstance(obj, self._constructor):
obj = obj.obj
for attr in self._attributes:
if attr not in kwargs:
kwargs[attr] = getattr(self, attr)
return self._constructor(obj, **kwargs)


class IndexOpsMixin:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -10501,7 +10501,7 @@ def rolling(
cls.rolling = rolling

@doc(Expanding)
def expanding(self, min_periods=1, center=False, axis=0):
def expanding(self, min_periods=1, center=None, axis=0):
MBrouns marked this conversation as resolved.
Show resolved Hide resolved
axis = self._get_axis_number(axis)
return Expanding(self, min_periods=min_periods, center=center, axis=axis)

Expand Down
9 changes: 7 additions & 2 deletions pandas/core/groupby/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
SeriesGroupBy and the DataFrameGroupBy objects.
"""
import collections
import warnings

from pandas.core.dtypes.common import is_list_like, is_scalar

Expand Down Expand Up @@ -40,8 +41,12 @@ def _gotitem(self, key, ndim, subset=None):
groupby = self._groupby[key]
except IndexError:
groupby = self._groupby

self = type(self)(subset, groupby=groupby, parent=self, **kwargs)
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"The `center` argument on `expanding` will be removed in the future",
)
self = type(self)(subset, groupby=groupby, parent=self, **kwargs)
self._reset_cache()
if subset.ndim == 2:
if is_scalar(key) and key in subset or is_list_like(key):
Expand Down
18 changes: 16 additions & 2 deletions pandas/core/window/expanding.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from textwrap import dedent
from typing import Dict, Optional
import warnings

from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution, doc
Expand Down Expand Up @@ -57,7 +58,15 @@ class Expanding(_Rolling_and_Expanding):

_attributes = ["min_periods", "center", "axis"]

def __init__(self, obj, min_periods=1, center=False, axis=0, **kwargs):
def __init__(self, obj, min_periods=1, center=None, axis=0, **kwargs):
if center is not None:
warnings.warn(
"The `center` argument on `expanding` will be removed in the future",
FutureWarning,
stacklevel=3,
)
else:
center = False
MBrouns marked this conversation as resolved.
Show resolved Hide resolved
super().__init__(obj=obj, min_periods=min_periods, center=center, axis=axis)

@property
Expand Down Expand Up @@ -129,7 +138,12 @@ def aggregate(self, func, *args, **kwargs):
@Substitution(name="expanding")
@Appender(_shared_docs["count"])
def count(self, **kwargs):
return super().count(**kwargs)
with warnings.catch_warnings():
MBrouns marked this conversation as resolved.
Show resolved Hide resolved
warnings.filterwarnings(
"ignore",
"The `center` argument on `expanding` will be removed in the future",
)
return super().count(**kwargs)

@Substitution(name="expanding")
@Appender(_shared_docs["apply"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ def test_expanding_corr_pairwise(frame):
ids=["sum", "mean", "max", "min"],
)
def test_expanding_func(func, static_comp, has_min_periods, series, frame, nan_locs):
def expanding_func(x, min_periods=1, center=False, axis=0):
exp = x.expanding(min_periods=min_periods, center=center, axis=axis)
def expanding_func(x, min_periods=1, axis=0):
exp = x.expanding(min_periods=min_periods, axis=axis)
return getattr(exp, func)()

_check_expanding(
Expand Down Expand Up @@ -166,7 +166,7 @@ def test_expanding_apply_consistency(

with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
"ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning
)
# test consistency between expanding_xyz() and either (a)
# expanding_apply of Series.xyz(), or (b) expanding_apply of
Expand Down Expand Up @@ -267,7 +267,7 @@ def test_expanding_consistency(consistency_data, min_periods):
# with empty/0-length Series/DataFrames
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning,
"ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning
)

# test consistency between different expanding_* moments
Expand Down Expand Up @@ -454,7 +454,7 @@ def test_expanding_cov_pairwise_diff_length():
def test_expanding_corr_pairwise_diff_length():
# GH 7512
df1 = DataFrame(
[[1, 2], [3, 2], [3, 4]], columns=["A", "B"], index=Index(range(3), name="bar"),
[[1, 2], [3, 2], [3, 4]], columns=["A", "B"], index=Index(range(3), name="bar")
)
df1a = DataFrame(
[[1, 2], [3, 4]], index=Index([0, 2], name="bar"), columns=["A", "B"]
Expand Down
11 changes: 2 additions & 9 deletions pandas/tests/window/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ def test_agg():

with pytest.raises(SpecificationError, match=msg):
r.aggregate(
{
"A": {"mean": "mean", "sum": "sum"},
"B": {"mean2": "mean", "sum2": "sum"},
}
{"A": {"mean": "mean", "sum": "sum"}, "B": {"mean2": "mean", "sum2": "sum"}}
)

result = r.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]})
Expand Down Expand Up @@ -191,11 +188,7 @@ def test_count_nonnumeric_types():
"dt_nat",
"periods_nat",
]
dt_nat_col = [
Timestamp("20170101"),
Timestamp("20170203"),
Timestamp(None),
]
dt_nat_col = [Timestamp("20170101"), Timestamp("20170203"), Timestamp(None)]

df = DataFrame(
{
Expand Down
20 changes: 13 additions & 7 deletions pandas/tests/window/test_expanding.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,17 @@ def test_doc_string():

def test_constructor(which):
# GH 12669

c = which.expanding

# valid
c(min_periods=1)
c(min_periods=1, center=True)
c(min_periods=1, center=False)

# not valid
for w in [2.0, "foo", np.array([2])]:
msg = "min_periods must be an integer"
with pytest.raises(ValueError, match=msg):
c(min_periods=w)

msg = "center must be a boolean"
MBrouns marked this conversation as resolved.
Show resolved Hide resolved
with pytest.raises(ValueError, match=msg):
c(min_periods=1, center=w)


@pytest.mark.parametrize("method", ["std", "mean", "sum", "max", "min", "var"])
def test_numpy_compat(method):
Expand Down Expand Up @@ -213,3 +206,16 @@ def test_iter_expanding_series(ser, expected, min_periods):

for (expected, actual) in zip(expected, ser.expanding(min_periods)):
tm.assert_series_equal(actual, expected)


def test_center_deprecate_warning():
# GH 20647
df = pd.DataFrame()
with tm.assert_produces_warning(FutureWarning):
df.expanding(center=True)

with tm.assert_produces_warning(FutureWarning):
df.expanding(center=False)

with tm.assert_produces_warning(None):
df.expanding()