Skip to content

Commit 55ad26a

Browse files
committed
clean pandas/core/window/rolling.py
1 parent dd26b71 commit 55ad26a

File tree

1 file changed

+28
-37
lines changed

1 file changed

+28
-37
lines changed

pandas/core/window/rolling.py

Lines changed: 28 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def validate(self):
117117
]:
118118
raise ValueError("closed must be 'right', 'left', 'both' or 'neither'")
119119
if not isinstance(self.obj, (ABCSeries, ABCDataFrame)):
120-
raise TypeError("invalid type: {}".format(type(self)))
120+
raise TypeError(f"invalid type: {type(self)}")
121121

122122
def _create_blocks(self):
123123
"""
@@ -163,9 +163,7 @@ def __getattr__(self, attr):
163163
if attr in self.obj:
164164
return self[attr]
165165

166-
raise AttributeError(
167-
"%r object has no attribute %r" % (type(self).__name__, attr)
168-
)
166+
raise AttributeError(f"{type(self).__name__} object has no attribute {attr}")
169167

170168
def _dir_additions(self):
171169
return self.obj._dir_additions()
@@ -212,17 +210,16 @@ def __repr__(self) -> str:
212210
"""
213211

214212
attrs = (
215-
"{k}={v}".format(k=k, v=getattr(self, k))
213+
"{k}={getattr(self, k)}"
216214
for k in self._attributes
217215
if getattr(self, k, None) is not None
218216
)
219-
return "{klass} [{attrs}]".format(
220-
klass=self._window_type, attrs=",".join(attrs)
221-
)
217+
attrs = ",".join(attrs)
218+
return f"{self._window_type} [{attrs}]"
222219

223220
def __iter__(self):
224221
url = "https://github.com/pandas-dev/pandas/issues/11704"
225-
raise NotImplementedError("See issue #11704 {url}".format(url=url))
222+
raise NotImplementedError(f"See issue #11704 {url}")
226223

227224
def _get_index(self) -> Optional[np.ndarray]:
228225
"""
@@ -250,15 +247,15 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray:
250247
values = ensure_float64(values)
251248
elif needs_i8_conversion(values.dtype):
252249
raise NotImplementedError(
253-
"ops for {action} for this "
254-
"dtype {dtype} are not "
255-
"implemented".format(action=self._window_type, dtype=values.dtype)
250+
f"ops for {self._window_type} for this "
251+
f"dtype {values.dtype} are not "
252+
"implemented"
256253
)
257254
else:
258255
try:
259256
values = ensure_float64(values)
260257
except (ValueError, TypeError):
261-
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
258+
raise TypeError(f"cannot handle this type -> {values.dtype}")
262259

263260
# Convert inf to nan for C funcs
264261
inf = np.isinf(values)
@@ -383,8 +380,7 @@ def _get_roll_func(self, func_name: str) -> Callable:
383380
window_func = getattr(window_aggregations, func_name, None)
384381
if window_func is None:
385382
raise ValueError(
386-
"we do not support this function "
387-
"in window_aggregations.{func_name}".format(func_name=func_name)
383+
"we do not support this function " f"in window_aggregations.{func_name}"
388384
)
389385
return window_func
390386

@@ -395,10 +391,8 @@ def _get_cython_func_type(self, func):
395391
Variable algorithms do not use window while fixed do.
396392
"""
397393
if self.is_freq_type:
398-
return self._get_roll_func("{}_variable".format(func))
399-
return partial(
400-
self._get_roll_func("{}_fixed".format(func)), win=self._get_window()
401-
)
394+
return self._get_roll_func(f"{func}_variable")
395+
return partial(self._get_roll_func(f"{func}_fixed"), win=self._get_window())
402396

403397
def _get_window_indexer(self):
404398
"""
@@ -917,11 +911,11 @@ def validate(self):
917911
import scipy.signal as sig
918912

919913
if not isinstance(self.win_type, str):
920-
raise ValueError("Invalid win_type {0}".format(self.win_type))
914+
raise ValueError(f"Invalid win_type {self.win_type}")
921915
if getattr(sig, self.win_type, None) is None:
922-
raise ValueError("Invalid win_type {0}".format(self.win_type))
916+
raise ValueError(f"Invalid win_type {self.win_type}")
923917
else:
924-
raise ValueError("Invalid window {0}".format(window))
918+
raise ValueError(f"Invalid window {window}")
925919

926920
def _get_win_type(self, kwargs: Dict) -> Union[str, Tuple]:
927921
"""
@@ -958,11 +952,10 @@ def _validate_win_type(win_type, kwargs):
958952
return win_type
959953

960954
def _pop_args(win_type, arg_names, kwargs):
961-
msg = "%s window requires %%s" % win_type
962955
all_args = []
963956
for n in arg_names:
964957
if n not in kwargs:
965-
raise ValueError(msg % n)
958+
raise ValueError(f"{win_type} window requires {n}")
966959
all_args.append(kwargs.pop(n))
967960
return all_args
968961

@@ -1634,12 +1627,12 @@ def _get_cov(X, Y):
16341627
16351628
>>> v1 = [3, 3, 3, 5, 8]
16361629
>>> v2 = [3, 4, 4, 4, 8]
1637-
>>> fmt = "{0:.6f}" # limit the printed precision to 6 digits
1630+
>>> precision = 6 # limit the printed precision to 6 digits
16381631
>>> # numpy returns a 2X2 array, the correlation coefficient
16391632
>>> # is the number at entry [0][1]
1640-
>>> print(fmt.format(np.corrcoef(v1[:-1], v2[:-1])[0][1]))
1633+
>>> print(f"{np.corrcoef(v1[:-1], v2[:-1])[0][1]:.{precision}f}")
16411634
0.333333
1642-
>>> print(fmt.format(np.corrcoef(v1[1:], v2[1:])[0][1]))
1635+
>>> print(f"{np.corrcoef(v1[1:], v2[1:])[0][1]:.{precision}f}")
16431636
0.916949
16441637
>>> s1 = pd.Series(v1)
16451638
>>> s2 = pd.Series(v2)
@@ -1729,9 +1722,9 @@ def _on(self) -> Index:
17291722
return Index(self.obj[self.on])
17301723
else:
17311724
raise ValueError(
1732-
"invalid on specified as {on}, "
1725+
f"invalid on specified as {self.on}, "
17331726
"must be a column (of DataFrame), an Index "
1734-
"or None".format(on=self.on)
1727+
"or None"
17351728
)
17361729

17371730
def validate(self):
@@ -1780,9 +1773,7 @@ def _validate_monotonic(self):
17801773
formatted = self.on
17811774
if self.on is None:
17821775
formatted = "index"
1783-
raise ValueError(
1784-
"{formatted} must be monotonic".format(formatted=formatted)
1785-
)
1776+
raise ValueError(f"{formatted} must be monotonic")
17861777

17871778
def _validate_freq(self):
17881779
"""
@@ -1794,9 +1785,9 @@ def _validate_freq(self):
17941785
return to_offset(self.window)
17951786
except (TypeError, ValueError):
17961787
raise ValueError(
1797-
"passed window {window} is not "
1788+
f"passed window {self.window} is not "
17981789
"compatible with a datetimelike "
1799-
"index".format(window=self.window)
1790+
"index"
18001791
)
18011792

18021793
_agg_see_also_doc = dedent(
@@ -1941,11 +1932,11 @@ def skew(self, **kwargs):
19411932
four matching the equivalent function call using `scipy.stats`.
19421933
19431934
>>> arr = [1, 2, 3, 4, 999]
1944-
>>> fmt = "{0:.6f}" # limit the printed precision to 6 digits
1935+
>>> precision = 6 # limit the printed precision to 6 digits
19451936
>>> import scipy.stats
1946-
>>> print(fmt.format(scipy.stats.kurtosis(arr[:-1], bias=False)))
1937+
>>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.{precision}f}")
19471938
-1.200000
1948-
>>> print(fmt.format(scipy.stats.kurtosis(arr[1:], bias=False)))
1939+
>>> print(f"{scipy.stats.kurtosis(arr[1:], bias=False):.{precision}f}")
19491940
3.999946
19501941
>>> s = pd.Series(arr)
19511942
>>> s.rolling(4).kurt()

0 commit comments

Comments
 (0)