Skip to content

Commit 04fce81

Browse files
makeajourneytopper-123
authored andcommitted
CLN: changed .format to f-string in pandas/core/indexes (pandas-dev#30273)
1 parent 2892b95 commit 04fce81

11 files changed

+73
-107
lines changed

pandas/core/indexes/accessors.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
2626
def __init__(self, data, orig):
2727
if not isinstance(data, ABCSeries):
2828
raise TypeError(
29-
"cannot convert an object of type {0} to a "
30-
"datetimelike index".format(type(data))
29+
f"cannot convert an object of type {type(data)} to a "
30+
"datetimelike index"
3131
)
3232

3333
self._parent = data
@@ -54,8 +54,7 @@ def _get_values(self):
5454
return DatetimeIndex(data, copy=False, name=self.name)
5555

5656
raise TypeError(
57-
"cannot convert an object of type {0} to a "
58-
"datetimelike index".format(type(data))
57+
f"cannot convert an object of type {type(data)} to a datetimelike index"
5958
)
6059

6160
def _delegate_property_get(self, name):
@@ -315,8 +314,8 @@ def __new__(cls, data):
315314

316315
if not isinstance(data, ABCSeries):
317316
raise TypeError(
318-
"cannot convert an object of type {0} to a "
319-
"datetimelike index".format(type(data))
317+
f"cannot convert an object of type {type(data)} to a "
318+
"datetimelike index"
320319
)
321320

322321
orig = data if is_categorical_dtype(data) else None

pandas/core/indexes/category.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -893,7 +893,7 @@ def _add_comparison_methods(cls):
893893
""" add in comparison methods """
894894

895895
def _make_compare(op):
896-
opname = "__{op}__".format(op=op.__name__)
896+
opname = f"__{op.__name__}__"
897897

898898
def _evaluate_compare(self, other):
899899
with np.errstate(all="ignore"):

pandas/core/indexes/datetimelike.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def wrapper(self, other):
137137
return result
138138

139139
wrapper.__doc__ = op.__doc__
140-
wrapper.__name__ = "__{}__".format(op.__name__)
140+
wrapper.__name__ = f"__{op.__name__}__"
141141
return wrapper
142142

143143
@property
@@ -677,7 +677,7 @@ def _summary(self, name=None):
677677
name = type(self).__name__
678678
result = f"{name}: {len(self)} entries{index_summary}"
679679
if self.freq:
680-
result += "\nFreq: %s" % self.freqstr
680+
result += f"\nFreq: {self.freqstr}"
681681

682682
# display as values, not quoted
683683
result = result.replace("'", "")

pandas/core/indexes/datetimes.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -247,10 +247,8 @@ def __new__(
247247

248248
if is_scalar(data):
249249
raise TypeError(
250-
"{cls}() must be called with a "
251-
"collection of some kind, {data} was passed".format(
252-
cls=cls.__name__, data=repr(data)
253-
)
250+
f"{cls.__name__}() must be called with a "
251+
f"collection of some kind, {repr(data)} was passed"
254252
)
255253

256254
# - Cases checked above all return/raise before reaching here - #
@@ -973,9 +971,7 @@ def get_loc(self, key, method=None, tolerance=None):
973971
elif isinstance(key, timedelta):
974972
# GH#20464
975973
raise TypeError(
976-
"Cannot index {cls} with {other}".format(
977-
cls=type(self).__name__, other=type(key).__name__
978-
)
974+
f"Cannot index {type(self).__name__} with {type(key).__name__}"
979975
)
980976

981977
if isinstance(key, time):
@@ -1577,13 +1573,13 @@ def bdate_range(
15771573
weekmask = weekmask or "Mon Tue Wed Thu Fri"
15781574
freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask)
15791575
except (KeyError, TypeError):
1580-
msg = "invalid custom frequency string: {freq}".format(freq=freq)
1576+
msg = f"invalid custom frequency string: {freq}"
15811577
raise ValueError(msg)
15821578
elif holidays or weekmask:
15831579
msg = (
15841580
"a custom frequency string is required when holidays or "
1585-
"weekmask are passed, got frequency {freq}"
1586-
).format(freq=freq)
1581+
f"weekmask are passed, got frequency {freq}"
1582+
)
15871583
raise ValueError(msg)
15881584

15891585
return date_range(

pandas/core/indexes/frozen.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,7 @@ def __hash__(self):
9393

9494
def _disabled(self, *args, **kwargs):
9595
"""This method will not function because object is immutable."""
96-
raise TypeError(
97-
"'{cls}' does not support mutable operations.".format(
98-
cls=type(self).__name__
99-
)
100-
)
96+
raise TypeError(f"'{type(self).__name__}' does not support mutable operations.")
10197

10298
def __str__(self) -> str:
10399
return pprint_thing(self, quote_strings=True, escape_chars=("\t", "\r", "\n"))

pandas/core/indexes/interval.py

+20-27
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,10 @@ def func(intvidx_self, other, sort=False):
154154
common_subtype = find_common_type(subtypes)
155155
if is_object_dtype(common_subtype):
156156
msg = (
157-
"can only do {op} between two IntervalIndex "
157+
f"can only do {self.op_name} between two IntervalIndex "
158158
"objects that have compatible dtypes"
159159
)
160-
raise TypeError(msg.format(op=self.op_name))
160+
raise TypeError(msg)
161161

162162
return setop(intvidx_self, other, sort)
163163

@@ -432,8 +432,7 @@ def closed(self):
432432
)
433433
def set_closed(self, closed):
434434
if closed not in _VALID_CLOSED:
435-
msg = "invalid option for 'closed': {closed}"
436-
raise ValueError(msg.format(closed=closed))
435+
raise ValueError(f"invalid option for 'closed': {closed}")
437436

438437
# return self._shallow_copy(closed=closed)
439438
array = self._data.set_closed(closed)
@@ -762,12 +761,12 @@ def _maybe_convert_i8(self, key):
762761

763762
# ensure consistency with IntervalIndex subtype
764763
subtype = self.dtype.subtype
765-
msg = (
766-
"Cannot index an IntervalIndex of subtype {subtype} with "
767-
"values of dtype {other}"
768-
)
764+
769765
if not is_dtype_equal(subtype, key_dtype):
770-
raise ValueError(msg.format(subtype=subtype, other=key_dtype))
766+
raise ValueError(
767+
f"Cannot index an IntervalIndex of subtype {subtype} with "
768+
f"values of dtype {key_dtype}"
769+
)
771770

772771
return key_i8
773772

@@ -776,8 +775,8 @@ def _check_method(self, method):
776775
return
777776

778777
if method in ["bfill", "backfill", "pad", "ffill", "nearest"]:
779-
msg = "method {method} not yet implemented for IntervalIndex"
780-
raise NotImplementedError(msg.format(method=method))
778+
msg = f"method {method} not yet implemented for IntervalIndex"
779+
raise NotImplementedError(msg)
781780

782781
raise ValueError("Invalid fill method")
783782

@@ -1165,36 +1164,34 @@ def _format_data(self, name=None):
11651164
summary = "[]"
11661165
elif n == 1:
11671166
first = formatter(self[0])
1168-
summary = "[{first}]".format(first=first)
1167+
summary = f"[{first}]"
11691168
elif n == 2:
11701169
first = formatter(self[0])
11711170
last = formatter(self[-1])
1172-
summary = "[{first}, {last}]".format(first=first, last=last)
1171+
summary = f"[{first}, {last}]"
11731172
else:
11741173

11751174
if n > max_seq_items:
11761175
n = min(max_seq_items // 2, 10)
11771176
head = [formatter(x) for x in self[:n]]
11781177
tail = [formatter(x) for x in self[-n:]]
1179-
summary = "[{head} ... {tail}]".format(
1180-
head=", ".join(head), tail=", ".join(tail)
1181-
)
1178+
summary = f"[{', '.join(head)} ... {', '.join(tail)}]"
11821179
else:
11831180
tail = [formatter(x) for x in self]
1184-
summary = "[{tail}]".format(tail=", ".join(tail))
1181+
summary = f"[{', '.join(tail)}]"
11851182

11861183
return summary + "," + self._format_space()
11871184

11881185
def _format_attrs(self):
11891186
attrs = [("closed", repr(self.closed))]
11901187
if self.name is not None:
11911188
attrs.append(("name", default_pprint(self.name)))
1192-
attrs.append(("dtype", "'{dtype}'".format(dtype=self.dtype)))
1189+
attrs.append(("dtype", f"'{self.dtype}'"))
11931190
return attrs
11941191

11951192
def _format_space(self):
11961193
space = " " * (len(type(self).__name__) + 1)
1197-
return "\n{space}".format(space=space)
1194+
return f"\n{space}"
11981195

11991196
# --------------------------------------------------------------------
12001197

@@ -1490,25 +1487,21 @@ def interval_range(
14901487
)
14911488

14921489
if not _is_valid_endpoint(start):
1493-
msg = "start must be numeric or datetime-like, got {start}"
1494-
raise ValueError(msg.format(start=start))
1490+
raise ValueError(f"start must be numeric or datetime-like, got {start}")
14951491
elif not _is_valid_endpoint(end):
1496-
msg = "end must be numeric or datetime-like, got {end}"
1497-
raise ValueError(msg.format(end=end))
1492+
raise ValueError(f"end must be numeric or datetime-like, got {end}")
14981493

14991494
if is_float(periods):
15001495
periods = int(periods)
15011496
elif not is_integer(periods) and periods is not None:
1502-
msg = "periods must be a number, got {periods}"
1503-
raise TypeError(msg.format(periods=periods))
1497+
raise TypeError(f"periods must be a number, got {periods}")
15041498

15051499
if freq is not None and not is_number(freq):
15061500
try:
15071501
freq = to_offset(freq)
15081502
except ValueError:
15091503
raise ValueError(
1510-
"freq must be numeric or convertible to "
1511-
"DateOffset, got {freq}".format(freq=freq)
1504+
f"freq must be numeric or convertible to DateOffset, got {freq}"
15121505
)
15131506

15141507
# verify type compatibility

pandas/core/indexes/multi.py

+23-34
Original file line numberDiff line numberDiff line change
@@ -343,35 +343,26 @@ def _verify_integrity(self, codes=None, levels=None):
343343
for i, (level, level_codes) in enumerate(zip(levels, codes)):
344344
if len(level_codes) != codes_length:
345345
raise ValueError(
346-
"Unequal code lengths: %s" % ([len(code_) for code_ in codes])
346+
f"Unequal code lengths: {[len(code_) for code_ in codes]}"
347347
)
348348
if len(level_codes) and level_codes.max() >= len(level):
349-
msg = (
350-
"On level {level}, code max ({max_code}) >= length of "
351-
"level ({level_len}). NOTE: this index is in an "
352-
"inconsistent state".format(
353-
level=i, max_code=level_codes.max(), level_len=len(level)
354-
)
355-
)
356-
raise ValueError(msg)
357-
if len(level_codes) and level_codes.min() < -1:
358349
raise ValueError(
359-
"On level {level}, code value ({code})"
360-
" < -1".format(level=i, code=level_codes.min())
350+
f"On level {i}, code max ({level_codes.max()}) >= length of "
351+
f"level ({len(level)}). NOTE: this index is in an "
352+
"inconsistent state"
361353
)
354+
if len(level_codes) and level_codes.min() < -1:
355+
raise ValueError(f"On level {i}, code value ({level_codes.min()}) < -1")
362356
if not level.is_unique:
363357
raise ValueError(
364-
"Level values must be unique: {values} on "
365-
"level {level}".format(values=list(level), level=i)
358+
f"Level values must be unique: {list(level)} on level {i}"
366359
)
367360
if self.sortorder is not None:
368361
if self.sortorder > self._lexsort_depth():
369362
raise ValueError(
370-
"Value for sortorder must be inferior or equal "
371-
"to actual lexsort_depth: "
372-
"sortorder {sortorder} with lexsort_depth {lexsort_depth}".format(
373-
sortorder=self.sortorder, lexsort_depth=self._lexsort_depth()
374-
)
363+
"Value for sortorder must be inferior or equal to actual "
364+
f"lexsort_depth: sortorder {self.sortorder} "
365+
f"with lexsort_depth {self._lexsort_depth()}"
375366
)
376367

377368
codes = [
@@ -1241,7 +1232,7 @@ def _set_names(self, names, level=None, validate=True):
12411232
# All items in 'names' need to be hashable:
12421233
if not is_hashable(name):
12431234
raise TypeError(
1244-
"{}.name must be a hashable type".format(type(self).__name__)
1235+
f"{type(self).__name__}.name must be a hashable type"
12451236
)
12461237
self._names[lev] = name
12471238

@@ -1312,8 +1303,8 @@ def _get_level_number(self, level) -> int:
13121303
# Note: levels are zero-based
13131304
elif level >= self.nlevels:
13141305
raise IndexError(
1315-
"Too many levels: Index has only %d levels, "
1316-
"not %d" % (self.nlevels, level + 1)
1306+
f"Too many levels: Index has only {self.nlevels} levels, "
1307+
f"not {level + 1}"
13171308
)
13181309
return level
13191310

@@ -1465,7 +1456,7 @@ def dropna(self, how="any"):
14651456
elif how == "all":
14661457
indexer = np.all(nans, axis=0)
14671458
else:
1468-
raise ValueError("invalid how option: {0}".format(how))
1459+
raise ValueError(f"invalid how option: {how}")
14691460

14701461
new_codes = [level_codes[~indexer] for level_codes in self.codes]
14711462
return self.copy(codes=new_codes, deep=True)
@@ -2103,7 +2094,7 @@ def drop(self, codes, level=None, errors="raise"):
21032094
loc = loc.nonzero()[0]
21042095
inds.extend(loc)
21052096
else:
2106-
msg = "unsupported indexer of type {}".format(type(loc))
2097+
msg = f"unsupported indexer of type {type(loc)}"
21072098
raise AssertionError(msg)
21082099
except KeyError:
21092100
if errors != "ignore":
@@ -2330,7 +2321,7 @@ def _convert_listlike_indexer(self, keyarr, kind=None):
23302321
check = self.levels[0].get_indexer(keyarr)
23312322
mask = check == -1
23322323
if mask.any():
2333-
raise KeyError("%s not in index" % keyarr[mask])
2324+
raise KeyError(f"{keyarr[mask]} not in index")
23342325

23352326
return indexer, keyarr
23362327

@@ -2600,8 +2591,7 @@ def _maybe_to_slice(loc):
26002591
keylen = len(key)
26012592
if self.nlevels < keylen:
26022593
raise KeyError(
2603-
"Key length ({0}) exceeds index depth ({1})"
2604-
"".format(keylen, self.nlevels)
2594+
f"Key length ({keylen}) exceeds index depth ({self.nlevels})"
26052595
)
26062596

26072597
if keylen == self.nlevels and self.is_unique:
@@ -2917,9 +2907,8 @@ def get_locs(self, seq):
29172907
true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s]
29182908
if true_slices and true_slices[-1] >= self.lexsort_depth:
29192909
raise UnsortedIndexError(
2920-
"MultiIndex slicing requires the index "
2921-
"to be lexsorted: slicing on levels {0}, "
2922-
"lexsort depth {1}".format(true_slices, self.lexsort_depth)
2910+
"MultiIndex slicing requires the index to be lexsorted: slicing "
2911+
f"on levels {true_slices}, lexsort depth {self.lexsort_depth}"
29232912
)
29242913
# indexer
29252914
# this is the list of all values that we want to select
@@ -3261,10 +3250,10 @@ def astype(self, dtype, copy=True):
32613250
msg = "> 1 ndim Categorical are not supported at this time"
32623251
raise NotImplementedError(msg)
32633252
elif not is_object_dtype(dtype):
3264-
msg = (
3265-
"Setting {cls} dtype to anything other than object is not supported"
3266-
).format(cls=type(self))
3267-
raise TypeError(msg)
3253+
raise TypeError(
3254+
f"Setting {type(self)} dtype to anything other "
3255+
"than object is not supported"
3256+
)
32683257
elif copy is True:
32693258
return self._shallow_copy()
32703259
return self

pandas/core/indexes/numeric.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -381,11 +381,10 @@ def inferred_type(self) -> str:
381381
def astype(self, dtype, copy=True):
382382
dtype = pandas_dtype(dtype)
383383
if needs_i8_conversion(dtype):
384-
msg = (
385-
"Cannot convert Float64Index to dtype {dtype}; integer "
384+
raise TypeError(
385+
f"Cannot convert Float64Index to dtype {dtype}; integer "
386386
"values are required for conversion"
387-
).format(dtype=dtype)
388-
raise TypeError(msg)
387+
)
389388
elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):
390389
# TODO(jreback); this can change once we have an EA Index type
391390
# GH 13149

0 commit comments

Comments
 (0)