Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 268c462

Browse files
authoredMay 15, 2020
CLN/TST: Remove Base Class and all subclasses and fixturize data (#34179)
1 parent c10020f commit 268c462

12 files changed

+2149
-2086
lines changed
 

‎pandas/tests/window/common.py

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,8 @@
1-
from datetime import datetime
2-
31
import numpy as np
4-
from numpy.random import randn
52

6-
from pandas import DataFrame, Series, bdate_range
3+
from pandas import Series
74
import pandas._testing as tm
85

9-
N, K = 100, 10
10-
11-
12-
class Base:
13-
14-
_nan_locs = np.arange(20, 40)
15-
_inf_locs = np.array([])
16-
17-
def _create_data(self):
18-
arr = randn(N)
19-
arr[self._nan_locs] = np.NaN
20-
21-
self.arr = arr
22-
self.rng = bdate_range(datetime(2009, 1, 1), periods=N)
23-
self.series = Series(arr.copy(), index=self.rng)
24-
self.frame = DataFrame(randn(N, K), index=self.rng, columns=np.arange(K))
25-
266

277
def check_pairwise_moment(frame, dispatch, name, **kwargs):
288
def get_result(obj, obj2=None):

‎pandas/tests/window/conftest.py

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
from datetime import datetime
2+
13
import numpy as np
4+
from numpy.random import randn
25
import pytest
36

47
import pandas.util._test_decorators as td
58

6-
from pandas import DataFrame, Series, notna
9+
from pandas import DataFrame, Series, bdate_range, notna
710

811

912
@pytest.fixture(params=[True, False])
@@ -242,3 +245,60 @@ def no_nans(x):
242245
def consistency_data(request):
243246
"""Create consistency data"""
244247
return request.param
248+
249+
250+
def _create_arr():
251+
"""Internal function to mock an array."""
252+
arr = randn(100)
253+
locs = np.arange(20, 40)
254+
arr[locs] = np.NaN
255+
return arr
256+
257+
258+
def _create_rng():
259+
"""Internal function to mock date range."""
260+
rng = bdate_range(datetime(2009, 1, 1), periods=100)
261+
return rng
262+
263+
264+
def _create_series():
265+
"""Internal function to mock Series."""
266+
arr = _create_arr()
267+
series = Series(arr.copy(), index=_create_rng())
268+
return series
269+
270+
271+
def _create_frame():
272+
"""Internal function to mock DataFrame."""
273+
rng = _create_rng()
274+
return DataFrame(randn(100, 10), index=rng, columns=np.arange(10))
275+
276+
277+
@pytest.fixture
278+
def nan_locs():
279+
"""Make a range as loc fixture."""
280+
return np.arange(20, 40)
281+
282+
283+
@pytest.fixture
284+
def arr():
285+
"""Make an array as fixture."""
286+
return _create_arr()
287+
288+
289+
@pytest.fixture
290+
def frame():
291+
"""Make mocked frame as fixture."""
292+
return _create_frame()
293+
294+
295+
@pytest.fixture
296+
def series():
297+
"""Make mocked series as fixture."""
298+
return _create_series()
299+
300+
301+
@pytest.fixture(params=[_create_series(), _create_frame()])
302+
def which(request):
303+
"""Turn parametrized which as fixture for series and frame"""
304+
return request.param

‎pandas/tests/window/moments/test_moments_consistency_ewm.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
from pandas import DataFrame, Series, concat
66
from pandas.tests.window.common import (
7-
Base,
87
check_binary_ew,
98
check_binary_ew_min_periods,
109
check_pairwise_moment,
@@ -19,13 +18,9 @@
1918
)
2019

2120

22-
class TestEwmMomentsConsistency(Base):
23-
def setup_method(self, method):
24-
self._create_data()
25-
26-
@pytest.mark.parametrize("func", ["cov", "corr"])
27-
def test_ewm_pairwise_cov_corr(self, func):
28-
check_pairwise_moment(self.frame, "ewm", func, span=10, min_periods=5)
21+
@pytest.mark.parametrize("func", ["cov", "corr"])
22+
def test_ewm_pairwise_cov_corr(func, frame):
23+
check_pairwise_moment(frame, "ewm", func, span=10, min_periods=5)
2924

3025

3126
@pytest.mark.parametrize("name", ["cov", "corr"])

‎pandas/tests/window/moments/test_moments_consistency_expanding.py

Lines changed: 107 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from pandas import DataFrame, Index, MultiIndex, Series, isna, notna
88
import pandas._testing as tm
99
from pandas.tests.window.common import (
10-
Base,
1110
moments_consistency_cov_data,
1211
moments_consistency_is_constant,
1312
moments_consistency_mock_mean,
@@ -18,132 +17,145 @@
1817
)
1918

2019

21-
class TestExpandingMomentsConsistency(Base):
22-
def setup_method(self, method):
23-
self._create_data()
20+
def _check_expanding(
21+
func, static_comp, preserve_nan=True, series=None, frame=None, nan_locs=None
22+
):
2423

25-
def test_expanding_corr(self):
26-
A = self.series.dropna()
27-
B = (A + randn(len(A)))[:-5]
24+
series_result = func(series)
25+
assert isinstance(series_result, Series)
26+
frame_result = func(frame)
27+
assert isinstance(frame_result, DataFrame)
2828

29-
result = A.expanding().corr(B)
29+
result = func(series)
30+
tm.assert_almost_equal(result[10], static_comp(series[:11]))
3031

31-
rolling_result = A.rolling(window=len(A), min_periods=1).corr(B)
32+
if preserve_nan:
33+
assert result.iloc[nan_locs].isna().all()
3234

33-
tm.assert_almost_equal(rolling_result, result)
3435

35-
def test_expanding_count(self):
36-
result = self.series.expanding(min_periods=0).count()
37-
tm.assert_almost_equal(
38-
result, self.series.rolling(window=len(self.series), min_periods=0).count()
39-
)
36+
def _check_expanding_has_min_periods(func, static_comp, has_min_periods):
37+
ser = Series(randn(50))
4038

41-
def test_expanding_quantile(self):
42-
result = self.series.expanding().quantile(0.5)
39+
if has_min_periods:
40+
result = func(ser, min_periods=30)
41+
assert result[:29].isna().all()
42+
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
4343

44-
rolling_result = self.series.rolling(
45-
window=len(self.series), min_periods=1
46-
).quantile(0.5)
44+
# min_periods is working correctly
45+
result = func(ser, min_periods=15)
46+
assert isna(result.iloc[13])
47+
assert notna(result.iloc[14])
4748

48-
tm.assert_almost_equal(result, rolling_result)
49+
ser2 = Series(randn(20))
50+
result = func(ser2, min_periods=5)
51+
assert isna(result[3])
52+
assert notna(result[4])
4953

50-
def test_expanding_cov(self):
51-
A = self.series
52-
B = (A + randn(len(A)))[:-5]
54+
# min_periods=0
55+
result0 = func(ser, min_periods=0)
56+
result1 = func(ser, min_periods=1)
57+
tm.assert_almost_equal(result0, result1)
58+
else:
59+
result = func(ser)
60+
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
5361

54-
result = A.expanding().cov(B)
5562

56-
rolling_result = A.rolling(window=len(A), min_periods=1).cov(B)
63+
def test_expanding_corr(series):
64+
A = series.dropna()
65+
B = (A + randn(len(A)))[:-5]
5766

58-
tm.assert_almost_equal(rolling_result, result)
67+
result = A.expanding().corr(B)
5968

60-
def test_expanding_cov_pairwise(self):
61-
result = self.frame.expanding().corr()
69+
rolling_result = A.rolling(window=len(A), min_periods=1).corr(B)
6270

63-
rolling_result = self.frame.rolling(
64-
window=len(self.frame), min_periods=1
65-
).corr()
71+
tm.assert_almost_equal(rolling_result, result)
6672

67-
tm.assert_frame_equal(result, rolling_result)
6873

69-
def test_expanding_corr_pairwise(self):
70-
result = self.frame.expanding().corr()
74+
def test_expanding_count(series):
75+
result = series.expanding(min_periods=0).count()
76+
tm.assert_almost_equal(
77+
result, series.rolling(window=len(series), min_periods=0).count()
78+
)
7179

72-
rolling_result = self.frame.rolling(
73-
window=len(self.frame), min_periods=1
74-
).corr()
75-
tm.assert_frame_equal(result, rolling_result)
7680

77-
@pytest.mark.parametrize("has_min_periods", [True, False])
78-
@pytest.mark.parametrize(
79-
"func,static_comp",
80-
[("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)],
81-
ids=["sum", "mean", "max", "min"],
82-
)
83-
def test_expanding_func(self, func, static_comp, has_min_periods):
84-
def expanding_func(x, min_periods=1, center=False, axis=0):
85-
exp = x.expanding(min_periods=min_periods, center=center, axis=axis)
86-
return getattr(exp, func)()
87-
88-
self._check_expanding(expanding_func, static_comp, preserve_nan=False)
89-
self._check_expanding_has_min_periods(
90-
expanding_func, static_comp, has_min_periods
91-
)
81+
def test_expanding_quantile(series):
82+
result = series.expanding().quantile(0.5)
83+
84+
rolling_result = series.rolling(window=len(series), min_periods=1).quantile(0.5)
85+
86+
tm.assert_almost_equal(result, rolling_result)
87+
9288

93-
@pytest.mark.parametrize("has_min_periods", [True, False])
94-
def test_expanding_apply(self, engine_and_raw, has_min_periods):
89+
def test_expanding_cov(series):
90+
A = series
91+
B = (A + randn(len(A)))[:-5]
9592

96-
engine, raw = engine_and_raw
93+
result = A.expanding().cov(B)
9794

98-
def expanding_mean(x, min_periods=1):
95+
rolling_result = A.rolling(window=len(A), min_periods=1).cov(B)
9996

100-
exp = x.expanding(min_periods=min_periods)
101-
result = exp.apply(lambda x: x.mean(), raw=raw, engine=engine)
102-
return result
97+
tm.assert_almost_equal(rolling_result, result)
10398

104-
# TODO(jreback), needed to add preserve_nan=False
105-
# here to make this pass
106-
self._check_expanding(expanding_mean, np.mean, preserve_nan=False)
107-
self._check_expanding_has_min_periods(expanding_mean, np.mean, has_min_periods)
10899

109-
def _check_expanding(self, func, static_comp, preserve_nan=True):
100+
def test_expanding_cov_pairwise(frame):
101+
result = frame.expanding().cov()
110102

111-
series_result = func(self.series)
112-
assert isinstance(series_result, Series)
113-
frame_result = func(self.frame)
114-
assert isinstance(frame_result, DataFrame)
103+
rolling_result = frame.rolling(window=len(frame), min_periods=1).cov()
115104

116-
result = func(self.series)
117-
tm.assert_almost_equal(result[10], static_comp(self.series[:11]))
105+
tm.assert_frame_equal(result, rolling_result)
118106

119-
if preserve_nan:
120-
assert result.iloc[self._nan_locs].isna().all()
121107

122-
def _check_expanding_has_min_periods(self, func, static_comp, has_min_periods):
123-
ser = Series(randn(50))
108+
def test_expanding_corr_pairwise(frame):
109+
result = frame.expanding().corr()
124110

125-
if has_min_periods:
126-
result = func(ser, min_periods=30)
127-
assert result[:29].isna().all()
128-
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
111+
rolling_result = frame.rolling(window=len(frame), min_periods=1).corr()
112+
tm.assert_frame_equal(result, rolling_result)
129113

130-
# min_periods is working correctly
131-
result = func(ser, min_periods=15)
132-
assert isna(result.iloc[13])
133-
assert notna(result.iloc[14])
134114

135-
ser2 = Series(randn(20))
136-
result = func(ser2, min_periods=5)
137-
assert isna(result[3])
138-
assert notna(result[4])
115+
@pytest.mark.parametrize("has_min_periods", [True, False])
116+
@pytest.mark.parametrize(
117+
"func,static_comp",
118+
[("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)],
119+
ids=["sum", "mean", "max", "min"],
120+
)
121+
def test_expanding_func(func, static_comp, has_min_periods, series, frame, nan_locs):
122+
def expanding_func(x, min_periods=1, center=False, axis=0):
123+
exp = x.expanding(min_periods=min_periods, center=center, axis=axis)
124+
return getattr(exp, func)()
125+
126+
_check_expanding(
127+
expanding_func,
128+
static_comp,
129+
preserve_nan=False,
130+
series=series,
131+
frame=frame,
132+
nan_locs=nan_locs,
133+
)
134+
_check_expanding_has_min_periods(expanding_func, static_comp, has_min_periods)
135+
139136

140-
# min_periods=0
141-
result0 = func(ser, min_periods=0)
142-
result1 = func(ser, min_periods=1)
143-
tm.assert_almost_equal(result0, result1)
144-
else:
145-
result = func(ser)
146-
tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
137+
@pytest.mark.parametrize("has_min_periods", [True, False])
138+
def test_expanding_apply(engine_and_raw, has_min_periods, series, frame, nan_locs):
139+
140+
engine, raw = engine_and_raw
141+
142+
def expanding_mean(x, min_periods=1):
143+
144+
exp = x.expanding(min_periods=min_periods)
145+
result = exp.apply(lambda x: x.mean(), raw=raw, engine=engine)
146+
return result
147+
148+
# TODO(jreback), needed to add preserve_nan=False
149+
# here to make this pass
150+
_check_expanding(
151+
expanding_mean,
152+
np.mean,
153+
preserve_nan=False,
154+
series=series,
155+
frame=frame,
156+
nan_locs=nan_locs,
157+
)
158+
_check_expanding_has_min_periods(expanding_mean, np.mean, has_min_periods)
147159

148160

149161
@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])

‎pandas/tests/window/moments/test_moments_consistency_rolling.py

Lines changed: 38 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import pandas._testing as tm
1313
from pandas.core.window.common import _flex_binary_moment
1414
from pandas.tests.window.common import (
15-
Base,
1615
check_pairwise_moment,
1716
moments_consistency_cov_data,
1817
moments_consistency_is_constant,
@@ -33,60 +32,56 @@ def _rolling_consistency_cases():
3332
yield window, min_periods, center
3433

3534

36-
class TestRollingMomentsConsistency(Base):
37-
def setup_method(self, method):
38-
self._create_data()
35+
# binary moments
36+
def test_rolling_cov(series):
37+
A = series
38+
B = A + randn(len(A))
3939

40-
# binary moments
41-
def test_rolling_cov(self):
42-
A = self.series
43-
B = A + randn(len(A))
40+
result = A.rolling(window=50, min_periods=25).cov(B)
41+
tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1])
4442

45-
result = A.rolling(window=50, min_periods=25).cov(B)
46-
tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1])
4743

48-
def test_rolling_corr(self):
49-
A = self.series
50-
B = A + randn(len(A))
44+
def test_rolling_corr(series):
45+
A = series
46+
B = A + randn(len(A))
5147

52-
result = A.rolling(window=50, min_periods=25).corr(B)
53-
tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1])
48+
result = A.rolling(window=50, min_periods=25).corr(B)
49+
tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1])
5450

55-
# test for correct bias correction
56-
a = tm.makeTimeSeries()
57-
b = tm.makeTimeSeries()
58-
a[:5] = np.nan
59-
b[:10] = np.nan
51+
# test for correct bias correction
52+
a = tm.makeTimeSeries()
53+
b = tm.makeTimeSeries()
54+
a[:5] = np.nan
55+
b[:10] = np.nan
6056

61-
result = a.rolling(window=len(a), min_periods=1).corr(b)
62-
tm.assert_almost_equal(result[-1], a.corr(b))
57+
result = a.rolling(window=len(a), min_periods=1).corr(b)
58+
tm.assert_almost_equal(result[-1], a.corr(b))
6359

64-
@pytest.mark.parametrize("func", ["cov", "corr"])
65-
def test_rolling_pairwise_cov_corr(self, func):
66-
check_pairwise_moment(self.frame, "rolling", func, window=10, min_periods=5)
6760

68-
@pytest.mark.parametrize("method", ["corr", "cov"])
69-
def test_flex_binary_frame(self, method):
70-
series = self.frame[1]
61+
@pytest.mark.parametrize("func", ["cov", "corr"])
62+
def test_rolling_pairwise_cov_corr(func, frame):
63+
check_pairwise_moment(frame, "rolling", func, window=10, min_periods=5)
7164

72-
res = getattr(series.rolling(window=10), method)(self.frame)
73-
res2 = getattr(self.frame.rolling(window=10), method)(series)
74-
exp = self.frame.apply(lambda x: getattr(series.rolling(window=10), method)(x))
7565

76-
tm.assert_frame_equal(res, exp)
77-
tm.assert_frame_equal(res2, exp)
66+
@pytest.mark.parametrize("method", ["corr", "cov"])
67+
def test_flex_binary_frame(method, frame):
68+
series = frame[1]
7869

79-
frame2 = self.frame.copy()
80-
frame2.values[:] = np.random.randn(*frame2.shape)
70+
res = getattr(series.rolling(window=10), method)(frame)
71+
res2 = getattr(frame.rolling(window=10), method)(series)
72+
exp = frame.apply(lambda x: getattr(series.rolling(window=10), method)(x))
8173

82-
res3 = getattr(self.frame.rolling(window=10), method)(frame2)
83-
exp = DataFrame(
84-
{
85-
k: getattr(self.frame[k].rolling(window=10), method)(frame2[k])
86-
for k in self.frame
87-
}
88-
)
89-
tm.assert_frame_equal(res3, exp)
74+
tm.assert_frame_equal(res, exp)
75+
tm.assert_frame_equal(res2, exp)
76+
77+
frame2 = frame.copy()
78+
frame2.values[:] = np.random.randn(*frame2.shape)
79+
80+
res3 = getattr(frame.rolling(window=10), method)(frame2)
81+
exp = DataFrame(
82+
{k: getattr(frame[k].rolling(window=10), method)(frame2[k]) for k in frame}
83+
)
84+
tm.assert_frame_equal(res3, exp)
9085

9186

9287
@pytest.mark.slow

‎pandas/tests/window/moments/test_moments_ewm.py

Lines changed: 236 additions & 245 deletions
Large diffs are not rendered by default.

‎pandas/tests/window/moments/test_moments_rolling.py

Lines changed: 863 additions & 828 deletions
Large diffs are not rendered by default.

‎pandas/tests/window/test_api.py

Lines changed: 285 additions & 280 deletions
Large diffs are not rendered by default.

‎pandas/tests/window/test_ewm.py

Lines changed: 44 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -5,66 +5,62 @@
55

66
from pandas import DataFrame, Series
77
from pandas.core.window import EWM
8-
from pandas.tests.window.common import Base
98

109

11-
class TestEWM(Base):
12-
def setup_method(self, method):
13-
self._create_data()
10+
def test_doc_string():
1411

15-
def test_doc_string(self):
12+
df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
13+
df
14+
df.ewm(com=0.5).mean()
1615

17-
df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
18-
df
19-
df.ewm(com=0.5).mean()
2016

21-
@pytest.mark.parametrize("which", ["series", "frame"])
22-
def test_constructor(self, which):
23-
o = getattr(self, which)
24-
c = o.ewm
17+
def test_constructor(which):
2518

26-
# valid
27-
c(com=0.5)
28-
c(span=1.5)
29-
c(alpha=0.5)
30-
c(halflife=0.75)
31-
c(com=0.5, span=None)
32-
c(alpha=0.5, com=None)
33-
c(halflife=0.75, alpha=None)
19+
c = which.ewm
3420

35-
# not valid: mutually exclusive
36-
with pytest.raises(ValueError):
37-
c(com=0.5, alpha=0.5)
38-
with pytest.raises(ValueError):
39-
c(span=1.5, halflife=0.75)
40-
with pytest.raises(ValueError):
41-
c(alpha=0.5, span=1.5)
21+
# valid
22+
c(com=0.5)
23+
c(span=1.5)
24+
c(alpha=0.5)
25+
c(halflife=0.75)
26+
c(com=0.5, span=None)
27+
c(alpha=0.5, com=None)
28+
c(halflife=0.75, alpha=None)
4229

43-
# not valid: com < 0
44-
with pytest.raises(ValueError):
45-
c(com=-0.5)
30+
# not valid: mutually exclusive
31+
with pytest.raises(ValueError):
32+
c(com=0.5, alpha=0.5)
33+
with pytest.raises(ValueError):
34+
c(span=1.5, halflife=0.75)
35+
with pytest.raises(ValueError):
36+
c(alpha=0.5, span=1.5)
4637

47-
# not valid: span < 1
48-
with pytest.raises(ValueError):
49-
c(span=0.5)
38+
# not valid: com < 0
39+
with pytest.raises(ValueError):
40+
c(com=-0.5)
41+
42+
# not valid: span < 1
43+
with pytest.raises(ValueError):
44+
c(span=0.5)
45+
46+
# not valid: halflife <= 0
47+
with pytest.raises(ValueError):
48+
c(halflife=0)
5049

51-
# not valid: halflife <= 0
50+
# not valid: alpha <= 0 or alpha > 1
51+
for alpha in (-0.5, 1.5):
5252
with pytest.raises(ValueError):
53-
c(halflife=0)
53+
c(alpha=alpha)
5454

55-
# not valid: alpha <= 0 or alpha > 1
56-
for alpha in (-0.5, 1.5):
57-
with pytest.raises(ValueError):
58-
c(alpha=alpha)
5955

60-
@pytest.mark.parametrize("method", ["std", "mean", "var"])
61-
def test_numpy_compat(self, method):
62-
# see gh-12811
63-
e = EWM(Series([2, 4, 6]), alpha=0.5)
56+
@pytest.mark.parametrize("method", ["std", "mean", "var"])
57+
def test_numpy_compat(method):
58+
# see gh-12811
59+
e = EWM(Series([2, 4, 6]), alpha=0.5)
6460

65-
msg = "numpy operations are not valid with window objects"
61+
msg = "numpy operations are not valid with window objects"
6662

67-
with pytest.raises(UnsupportedFunctionCall, match=msg):
68-
getattr(e, method)(1, 2, 3)
69-
with pytest.raises(UnsupportedFunctionCall, match=msg):
70-
getattr(e, method)(dtype=np.float64)
63+
with pytest.raises(UnsupportedFunctionCall, match=msg):
64+
getattr(e, method)(1, 2, 3)
65+
with pytest.raises(UnsupportedFunctionCall, match=msg):
66+
getattr(e, method)(dtype=np.float64)

‎pandas/tests/window/test_expanding.py

Lines changed: 104 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -7,112 +7,111 @@
77
from pandas import DataFrame, Series
88
import pandas._testing as tm
99
from pandas.core.window import Expanding
10-
from pandas.tests.window.common import Base
11-
12-
13-
class TestExpanding(Base):
14-
def setup_method(self, method):
15-
self._create_data()
16-
17-
def test_doc_string(self):
18-
19-
df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
20-
df
21-
df.expanding(2).sum()
22-
23-
@pytest.mark.parametrize("which", ["series", "frame"])
24-
def test_constructor(self, which):
25-
# GH 12669
26-
27-
o = getattr(self, which)
28-
c = o.expanding
29-
30-
# valid
31-
c(min_periods=1)
32-
c(min_periods=1, center=True)
33-
c(min_periods=1, center=False)
34-
35-
# not valid
36-
for w in [2.0, "foo", np.array([2])]:
37-
with pytest.raises(ValueError):
38-
c(min_periods=w)
39-
with pytest.raises(ValueError):
40-
c(min_periods=1, center=w)
41-
42-
@pytest.mark.parametrize("method", ["std", "mean", "sum", "max", "min", "var"])
43-
def test_numpy_compat(self, method):
44-
# see gh-12811
45-
e = Expanding(Series([2, 4, 6]), window=2)
46-
47-
msg = "numpy operations are not valid with window objects"
48-
49-
with pytest.raises(UnsupportedFunctionCall, match=msg):
50-
getattr(e, method)(1, 2, 3)
51-
with pytest.raises(UnsupportedFunctionCall, match=msg):
52-
getattr(e, method)(dtype=np.float64)
53-
54-
@pytest.mark.parametrize(
55-
"expander",
56-
[
57-
1,
58-
pytest.param(
59-
"ls",
60-
marks=pytest.mark.xfail(
61-
reason="GH#16425 expanding with offset not supported"
62-
),
10+
11+
12+
def test_doc_string():
13+
14+
df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
15+
df
16+
df.expanding(2).sum()
17+
18+
19+
def test_constructor(which):
20+
# GH 12669
21+
22+
c = which.expanding
23+
24+
# valid
25+
c(min_periods=1)
26+
c(min_periods=1, center=True)
27+
c(min_periods=1, center=False)
28+
29+
# not valid
30+
for w in [2.0, "foo", np.array([2])]:
31+
with pytest.raises(ValueError):
32+
c(min_periods=w)
33+
with pytest.raises(ValueError):
34+
c(min_periods=1, center=w)
35+
36+
37+
@pytest.mark.parametrize("method", ["std", "mean", "sum", "max", "min", "var"])
38+
def test_numpy_compat(method):
39+
# see gh-12811
40+
e = Expanding(Series([2, 4, 6]), window=2)
41+
42+
msg = "numpy operations are not valid with window objects"
43+
44+
with pytest.raises(UnsupportedFunctionCall, match=msg):
45+
getattr(e, method)(1, 2, 3)
46+
with pytest.raises(UnsupportedFunctionCall, match=msg):
47+
getattr(e, method)(dtype=np.float64)
48+
49+
50+
@pytest.mark.parametrize(
51+
"expander",
52+
[
53+
1,
54+
pytest.param(
55+
"ls",
56+
marks=pytest.mark.xfail(
57+
reason="GH#16425 expanding with offset not supported"
6358
),
64-
],
65-
)
66-
def test_empty_df_expanding(self, expander):
67-
# GH 15819 Verifies that datetime and integer expanding windows can be
68-
# applied to empty DataFrames
69-
70-
expected = DataFrame()
71-
result = DataFrame().expanding(expander).sum()
72-
tm.assert_frame_equal(result, expected)
73-
74-
# Verifies that datetime and integer expanding windows can be applied
75-
# to empty DataFrames with datetime index
76-
expected = DataFrame(index=pd.DatetimeIndex([]))
77-
result = DataFrame(index=pd.DatetimeIndex([])).expanding(expander).sum()
78-
tm.assert_frame_equal(result, expected)
79-
80-
def test_missing_minp_zero(self):
81-
# https://github.com/pandas-dev/pandas/pull/18921
82-
# minp=0
83-
x = pd.Series([np.nan])
84-
result = x.expanding(min_periods=0).sum()
85-
expected = pd.Series([0.0])
86-
tm.assert_series_equal(result, expected)
87-
88-
# minp=1
89-
result = x.expanding(min_periods=1).sum()
90-
expected = pd.Series([np.nan])
91-
tm.assert_series_equal(result, expected)
92-
93-
@pytest.mark.parametrize("klass", [pd.Series, pd.DataFrame])
94-
def test_iter_raises(self, klass):
95-
# https://github.com/pandas-dev/pandas/issues/11704
96-
# Iteration over a Window
97-
obj = klass([1, 2, 3, 4])
98-
with pytest.raises(NotImplementedError):
99-
iter(obj.expanding(2))
100-
101-
def test_expanding_axis(self, axis_frame):
102-
# see gh-23372.
103-
df = DataFrame(np.ones((10, 20)))
104-
axis = df._get_axis_number(axis_frame)
105-
106-
if axis == 0:
107-
expected = DataFrame(
108-
{i: [np.nan] * 2 + [float(j) for j in range(3, 11)] for i in range(20)}
109-
)
110-
else:
111-
# axis == 1
112-
expected = DataFrame([[np.nan] * 2 + [float(i) for i in range(3, 21)]] * 10)
113-
114-
result = df.expanding(3, axis=axis_frame).sum()
115-
tm.assert_frame_equal(result, expected)
59+
),
60+
],
61+
)
62+
def test_empty_df_expanding(expander):
63+
# GH 15819 Verifies that datetime and integer expanding windows can be
64+
# applied to empty DataFrames
65+
66+
expected = DataFrame()
67+
result = DataFrame().expanding(expander).sum()
68+
tm.assert_frame_equal(result, expected)
69+
70+
# Verifies that datetime and integer expanding windows can be applied
71+
# to empty DataFrames with datetime index
72+
expected = DataFrame(index=pd.DatetimeIndex([]))
73+
result = DataFrame(index=pd.DatetimeIndex([])).expanding(expander).sum()
74+
tm.assert_frame_equal(result, expected)
75+
76+
77+
def test_missing_minp_zero():
78+
# https://github.com/pandas-dev/pandas/pull/18921
79+
# minp=0
80+
x = pd.Series([np.nan])
81+
result = x.expanding(min_periods=0).sum()
82+
expected = pd.Series([0.0])
83+
tm.assert_series_equal(result, expected)
84+
85+
# minp=1
86+
result = x.expanding(min_periods=1).sum()
87+
expected = pd.Series([np.nan])
88+
tm.assert_series_equal(result, expected)
89+
90+
91+
@pytest.mark.parametrize("klass", [pd.Series, pd.DataFrame])
92+
def test_iter_raises(klass):
93+
# https://github.com/pandas-dev/pandas/issues/11704
94+
# Iteration over a Window
95+
obj = klass([1, 2, 3, 4])
96+
with pytest.raises(NotImplementedError):
97+
iter(obj.expanding(2))
98+
99+
100+
def test_expanding_axis(axis_frame):
101+
# see gh-23372.
102+
df = DataFrame(np.ones((10, 20)))
103+
axis = df._get_axis_number(axis_frame)
104+
105+
if axis == 0:
106+
expected = DataFrame(
107+
{i: [np.nan] * 2 + [float(j) for j in range(3, 11)] for i in range(20)}
108+
)
109+
else:
110+
# axis == 1
111+
expected = DataFrame([[np.nan] * 2 + [float(i) for i in range(3, 21)]] * 10)
112+
113+
result = df.expanding(3, axis=axis_frame).sum()
114+
tm.assert_frame_equal(result, expected)
116115

117116

118117
@pytest.mark.parametrize("constructor", [Series, DataFrame])

‎pandas/tests/window/test_rolling.py

Lines changed: 348 additions & 345 deletions
Large diffs are not rendered by default.

‎pandas/tests/window/test_window.py

Lines changed: 59 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -7,70 +7,62 @@
77
import pandas as pd
88
from pandas import Series
99
from pandas.core.window import Window
10-
from pandas.tests.window.common import Base
11-
12-
13-
@pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
14-
class TestWindow(Base):
15-
def setup_method(self, method):
16-
self._create_data()
17-
18-
@td.skip_if_no_scipy
19-
@pytest.mark.parametrize("which", ["series", "frame"])
20-
def test_constructor(self, which):
21-
# GH 12669
22-
23-
o = getattr(self, which)
24-
c = o.rolling
25-
26-
# valid
27-
c(win_type="boxcar", window=2, min_periods=1)
28-
c(win_type="boxcar", window=2, min_periods=1, center=True)
29-
c(win_type="boxcar", window=2, min_periods=1, center=False)
30-
31-
# not valid
32-
for w in [2.0, "foo", np.array([2])]:
33-
with pytest.raises(ValueError, match="min_periods must be an integer"):
34-
c(win_type="boxcar", window=2, min_periods=w)
35-
with pytest.raises(ValueError, match="center must be a boolean"):
36-
c(win_type="boxcar", window=2, min_periods=1, center=w)
37-
38-
for wt in ["foobar", 1]:
39-
with pytest.raises(ValueError, match="Invalid win_type"):
40-
c(win_type=wt, window=2)
41-
42-
@td.skip_if_no_scipy
43-
@pytest.mark.parametrize("which", ["series", "frame"])
44-
def test_constructor_with_win_type(self, which, win_types):
45-
# GH 12669
46-
o = getattr(self, which)
47-
c = o.rolling
48-
c(win_type=win_types, window=2)
49-
50-
@pytest.mark.parametrize("method", ["sum", "mean"])
51-
def test_numpy_compat(self, method):
52-
# see gh-12811
53-
w = Window(Series([2, 4, 6]), window=[0, 2])
54-
55-
msg = "numpy operations are not valid with window objects"
56-
57-
with pytest.raises(UnsupportedFunctionCall, match=msg):
58-
getattr(w, method)(1, 2, 3)
59-
with pytest.raises(UnsupportedFunctionCall, match=msg):
60-
getattr(w, method)(dtype=np.float64)
61-
62-
@td.skip_if_no_scipy
63-
@pytest.mark.parametrize("arg", ["median", "kurt", "skew"])
64-
def test_agg_function_support(self, arg):
65-
df = pd.DataFrame({"A": np.arange(5)})
66-
roll = df.rolling(2, win_type="triang")
67-
68-
msg = f"'{arg}' is not a valid function for 'Window' object"
69-
with pytest.raises(AttributeError, match=msg):
70-
roll.agg(arg)
71-
72-
with pytest.raises(AttributeError, match=msg):
73-
roll.agg([arg])
74-
75-
with pytest.raises(AttributeError, match=msg):
76-
roll.agg({"A": arg})
10+
11+
12+
@td.skip_if_no_scipy
13+
def test_constructor(which):
14+
# GH 12669
15+
c = which.rolling
16+
17+
# valid
18+
c(win_type="boxcar", window=2, min_periods=1)
19+
c(win_type="boxcar", window=2, min_periods=1, center=True)
20+
c(win_type="boxcar", window=2, min_periods=1, center=False)
21+
22+
# not valid
23+
for w in [2.0, "foo", np.array([2])]:
24+
with pytest.raises(ValueError, match="min_periods must be an integer"):
25+
c(win_type="boxcar", window=2, min_periods=w)
26+
with pytest.raises(ValueError, match="center must be a boolean"):
27+
c(win_type="boxcar", window=2, min_periods=1, center=w)
28+
29+
for wt in ["foobar", 1]:
30+
with pytest.raises(ValueError, match="Invalid win_type"):
31+
c(win_type=wt, window=2)
32+
33+
34+
@td.skip_if_no_scipy
35+
def test_constructor_with_win_type(which, win_types):
36+
# GH 12669
37+
c = which.rolling
38+
c(win_type=win_types, window=2)
39+
40+
41+
@pytest.mark.parametrize("method", ["sum", "mean"])
42+
def test_numpy_compat(method):
43+
# see gh-12811
44+
w = Window(Series([2, 4, 6]), window=[0, 2])
45+
46+
msg = "numpy operations are not valid with window objects"
47+
48+
with pytest.raises(UnsupportedFunctionCall, match=msg):
49+
getattr(w, method)(1, 2, 3)
50+
with pytest.raises(UnsupportedFunctionCall, match=msg):
51+
getattr(w, method)(dtype=np.float64)
52+
53+
54+
@td.skip_if_no_scipy
55+
@pytest.mark.parametrize("arg", ["median", "kurt", "skew"])
56+
def test_agg_function_support(arg):
57+
df = pd.DataFrame({"A": np.arange(5)})
58+
roll = df.rolling(2, win_type="triang")
59+
60+
msg = f"'{arg}' is not a valid function for 'Window' object"
61+
with pytest.raises(AttributeError, match=msg):
62+
roll.agg(arg)
63+
64+
with pytest.raises(AttributeError, match=msg):
65+
roll.agg([arg])
66+
67+
with pytest.raises(AttributeError, match=msg):
68+
roll.agg({"A": arg})

0 commit comments

Comments
 (0)
Please sign in to comment.