Skip to content

Commit 5569ee8

Browse files
ganevgvproost
authored andcommitted
CLN: f-string in pandas/core/window/* (pandas-dev#29952)
1 parent 74c043e commit 5569ee8

File tree

4 files changed

+32
-46
lines changed

4 files changed

+32
-46
lines changed

pandas/core/window/common.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -303,10 +303,7 @@ def calculate_min_periods(
303303
else:
304304
min_periods = max(required_min_periods, min_periods)
305305
if min_periods > window:
306-
raise ValueError(
307-
"min_periods {min_periods} must be <= "
308-
"window {window}".format(min_periods=min_periods, window=window)
309-
)
306+
raise ValueError(f"min_periods {min_periods} must be <= window {window}")
310307
elif min_periods > num_values:
311308
min_periods = num_values + 1
312309
elif min_periods < 0:

pandas/core/window/ewm.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def _apply(self, func, **kwargs):
232232
if cfunc is None:
233233
raise ValueError(
234234
"we do not support this function "
235-
"in window_aggregations.{func}".format(func=func)
235+
f"in window_aggregations.{func}"
236236
)
237237

238238
def func(arg):

pandas/core/window/expanding.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,9 @@ def skew(self, **kwargs):
209209
210210
>>> arr = [1, 2, 3, 4, 999]
211211
>>> import scipy.stats
212-
>>> fmt = "{0:.6f}" # limit the printed precision to 6 digits
213-
>>> print(fmt.format(scipy.stats.kurtosis(arr[:-1], bias=False)))
212+
>>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}")
214213
-1.200000
215-
>>> print(fmt.format(scipy.stats.kurtosis(arr, bias=False)))
214+
>>> print(f"{scipy.stats.kurtosis(arr, bias=False):.6f}")
216215
4.999874
217216
>>> s = pd.Series(arr)
218217
>>> s.expanding(4).kurt()

pandas/core/window/rolling.py

+28-38
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
"""
@@ -164,7 +164,7 @@ def __getattr__(self, attr):
164164
return self[attr]
165165

166166
raise AttributeError(
167-
"%r object has no attribute %r" % (type(self).__name__, attr)
167+
f"'{type(self).__name__}' object has no attribute '{attr}'"
168168
)
169169

170170
def _dir_additions(self):
@@ -211,18 +211,17 @@ def __repr__(self) -> str:
211211
Provide a nice str repr of our rolling object.
212212
"""
213213

214-
attrs = (
215-
"{k}={v}".format(k=k, v=getattr(self, k))
216-
for k in self._attributes
217-
if getattr(self, k, None) is not None
218-
)
219-
return "{klass} [{attrs}]".format(
220-
klass=self._window_type, attrs=",".join(attrs)
214+
attrs_list = (
215+
f"{attr_name}={getattr(self, attr_name)}"
216+
for attr_name in self._attributes
217+
if getattr(self, attr_name, None) is not None
221218
)
219+
attrs = ",".join(attrs_list)
220+
return f"{self._window_type} [{attrs}]"
222221

223222
def __iter__(self):
224223
url = "https://github.com/pandas-dev/pandas/issues/11704"
225-
raise NotImplementedError("See issue #11704 {url}".format(url=url))
224+
raise NotImplementedError(f"See issue #11704 {url}")
226225

227226
def _get_index(self) -> Optional[np.ndarray]:
228227
"""
@@ -250,15 +249,14 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray:
250249
values = ensure_float64(values)
251250
elif needs_i8_conversion(values.dtype):
252251
raise NotImplementedError(
253-
"ops for {action} for this "
254-
"dtype {dtype} are not "
255-
"implemented".format(action=self._window_type, dtype=values.dtype)
252+
f"ops for {self._window_type} for this "
253+
f"dtype {values.dtype} are not implemented"
256254
)
257255
else:
258256
try:
259257
values = ensure_float64(values)
260258
except (ValueError, TypeError):
261-
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
259+
raise TypeError(f"cannot handle this type -> {values.dtype}")
262260

263261
# Convert inf to nan for C funcs
264262
inf = np.isinf(values)
@@ -383,8 +381,7 @@ def _get_roll_func(self, func_name: str) -> Callable:
383381
window_func = getattr(window_aggregations, func_name, None)
384382
if window_func is None:
385383
raise ValueError(
386-
"we do not support this function "
387-
"in window_aggregations.{func_name}".format(func_name=func_name)
384+
f"we do not support this function in window_aggregations.{func_name}"
388385
)
389386
return window_func
390387

@@ -395,10 +392,8 @@ def _get_cython_func_type(self, func):
395392
Variable algorithms do not use window while fixed do.
396393
"""
397394
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-
)
395+
return self._get_roll_func(f"{func}_variable")
396+
return partial(self._get_roll_func(f"{func}_fixed"), win=self._get_window())
402397

403398
def _get_window_indexer(self):
404399
"""
@@ -917,11 +912,11 @@ def validate(self):
917912
import scipy.signal as sig
918913

919914
if not isinstance(self.win_type, str):
920-
raise ValueError("Invalid win_type {0}".format(self.win_type))
915+
raise ValueError(f"Invalid win_type {self.win_type}")
921916
if getattr(sig, self.win_type, None) is None:
922-
raise ValueError("Invalid win_type {0}".format(self.win_type))
917+
raise ValueError(f"Invalid win_type {self.win_type}")
923918
else:
924-
raise ValueError("Invalid window {0}".format(window))
919+
raise ValueError(f"Invalid window {window}")
925920

926921
def _get_win_type(self, kwargs: Dict) -> Union[str, Tuple]:
927922
"""
@@ -958,11 +953,10 @@ def _validate_win_type(win_type, kwargs):
958953
return win_type
959954

960955
def _pop_args(win_type, arg_names, kwargs):
961-
msg = "%s window requires %%s" % win_type
962956
all_args = []
963957
for n in arg_names:
964958
if n not in kwargs:
965-
raise ValueError(msg % n)
959+
raise ValueError(f"{win_type} window requires {n}")
966960
all_args.append(kwargs.pop(n))
967961
return all_args
968962

@@ -1634,12 +1628,11 @@ def _get_cov(X, Y):
16341628
16351629
>>> v1 = [3, 3, 3, 5, 8]
16361630
>>> v2 = [3, 4, 4, 4, 8]
1637-
>>> fmt = "{0:.6f}" # 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]:.6f}")
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]:.6f}")
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,10 @@ 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
19451935
>>> import scipy.stats
1946-
>>> print(fmt.format(scipy.stats.kurtosis(arr[:-1], bias=False)))
1936+
>>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}")
19471937
-1.200000
1948-
>>> print(fmt.format(scipy.stats.kurtosis(arr[1:], bias=False)))
1938+
>>> print(f"{scipy.stats.kurtosis(arr[1:], bias=False):.6f}")
19491939
3.999946
19501940
>>> s = pd.Series(arr)
19511941
>>> s.rolling(4).kurt()

0 commit comments

Comments
 (0)