Skip to content

Commit a46806c

Browse files
topper-123jreback
authored andcommitted
CLN: use f-strings in core.categorical.py (#29748)
1 parent 6d11aa8 commit a46806c

File tree

1 file changed

+35
-48
lines changed

1 file changed

+35
-48
lines changed

pandas/core/arrays/categorical.py

Lines changed: 35 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@
7373

7474

7575
def _cat_compare_op(op):
76-
opname = "__{op}__".format(op=op.__name__)
76+
opname = f"__{op.__name__}__"
7777

7878
@unpack_zerodim_and_defer(opname)
79-
def f(self, other):
79+
def func(self, other):
8080
# On python2, you can usually compare any type to any type, and
8181
# Categoricals can be seen as a custom type, but having different
8282
# results depending whether categories are the same or not is kind of
@@ -137,28 +137,26 @@ def f(self, other):
137137
elif opname == "__ne__":
138138
return np.repeat(True, len(self))
139139
else:
140-
msg = (
141-
"Cannot compare a Categorical for op {op} with a "
140+
raise TypeError(
141+
f"Cannot compare a Categorical for op {opname} with a "
142142
"scalar, which is not a category."
143143
)
144-
raise TypeError(msg.format(op=opname))
145144
else:
146145

147146
# allow categorical vs object dtype array comparisons for equality
148147
# these are only positional comparisons
149148
if opname in ["__eq__", "__ne__"]:
150149
return getattr(np.array(self), opname)(np.array(other))
151150

152-
msg = (
153-
"Cannot compare a Categorical for op {op} with type {typ}."
154-
"\nIf you want to compare values, use 'np.asarray(cat) "
155-
"<op> other'."
151+
raise TypeError(
152+
f"Cannot compare a Categorical for op {opname} with "
153+
f"type {type(other)}.\nIf you want to compare values, "
154+
"use 'np.asarray(cat) <op> other'."
156155
)
157-
raise TypeError(msg.format(op=opname, typ=type(other)))
158156

159-
f.__name__ = opname
157+
func.__name__ = opname
160158

161-
return f
159+
return func
162160

163161

164162
def contains(cat, key, container):
@@ -1060,11 +1058,9 @@ def add_categories(self, new_categories, inplace=False):
10601058
new_categories = [new_categories]
10611059
already_included = set(new_categories) & set(self.dtype.categories)
10621060
if len(already_included) != 0:
1063-
msg = (
1064-
"new categories must not include old categories: "
1065-
"{already_included!s}"
1061+
raise ValueError(
1062+
f"new categories must not include old categories: {already_included}"
10661063
)
1067-
raise ValueError(msg.format(already_included=already_included))
10681064
new_categories = list(self.dtype.categories) + list(new_categories)
10691065
new_dtype = CategoricalDtype(new_categories, self.ordered)
10701066

@@ -1120,8 +1116,7 @@ def remove_categories(self, removals, inplace=False):
11201116
new_categories = [x for x in new_categories if notna(x)]
11211117

11221118
if len(not_included) != 0:
1123-
msg = "removals must all be in old categories: {not_included!s}"
1124-
raise ValueError(msg.format(not_included=not_included))
1119+
raise ValueError(f"removals must all be in old categories: {not_included}")
11251120

11261121
return self.set_categories(
11271122
new_categories, ordered=self.ordered, rename=False, inplace=inplace
@@ -1299,9 +1294,8 @@ def shift(self, periods, fill_value=None):
12991294
fill_value = self.categories.get_loc(fill_value)
13001295
else:
13011296
raise ValueError(
1302-
"'fill_value={}' is not present "
1303-
"in this Categorical's "
1304-
"categories".format(fill_value)
1297+
f"'fill_value={fill_value}' is not present "
1298+
"in this Categorical's categories"
13051299
)
13061300
if periods > 0:
13071301
codes[:periods] = fill_value
@@ -1342,8 +1336,8 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
13421336
# for all other cases, raise for now (similarly as what happens in
13431337
# Series.__array_prepare__)
13441338
raise TypeError(
1345-
"Object with dtype {dtype} cannot perform "
1346-
"the numpy op {op}".format(dtype=self.dtype, op=ufunc.__name__)
1339+
f"Object with dtype {self.dtype} cannot perform "
1340+
f"the numpy op {ufunc.__name__}"
13471341
)
13481342

13491343
def __setstate__(self, state):
@@ -1542,9 +1536,9 @@ def check_for_ordered(self, op):
15421536
""" assert that we are ordered """
15431537
if not self.ordered:
15441538
raise TypeError(
1545-
"Categorical is not ordered for operation {op}\n"
1539+
f"Categorical is not ordered for operation {op}\n"
15461540
"you can use .as_ordered() to change the "
1547-
"Categorical to an ordered one\n".format(op=op)
1541+
"Categorical to an ordered one\n"
15481542
)
15491543

15501544
def _values_for_argsort(self):
@@ -1679,8 +1673,7 @@ def sort_values(self, inplace=False, ascending=True, na_position="last"):
16791673
"""
16801674
inplace = validate_bool_kwarg(inplace, "inplace")
16811675
if na_position not in ["last", "first"]:
1682-
msg = "invalid na_position: {na_position!r}"
1683-
raise ValueError(msg.format(na_position=na_position))
1676+
raise ValueError(f"invalid na_position: {na_position!r}")
16841677

16851678
sorted_idx = nargsort(self, ascending=ascending, na_position=na_position)
16861679

@@ -1836,8 +1829,7 @@ def fillna(self, value=None, method=None, limit=None):
18361829
else:
18371830
raise TypeError(
18381831
'"value" parameter must be a scalar, dict '
1839-
"or Series, but you passed a "
1840-
'"{0}"'.format(type(value).__name__)
1832+
f'or Series, but you passed a {type(value).__name__!r}"'
18411833
)
18421834

18431835
return self._constructor(codes, dtype=self.dtype, fastpath=True)
@@ -1930,8 +1922,11 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None):
19301922
if fill_value in self.categories:
19311923
fill_value = self.categories.get_loc(fill_value)
19321924
else:
1933-
msg = "'fill_value' ('{}') is not in this Categorical's categories."
1934-
raise TypeError(msg.format(fill_value))
1925+
msg = (
1926+
f"'fill_value' ('{fill_value}') is not in this "
1927+
"Categorical's categories."
1928+
)
1929+
raise TypeError(msg)
19351930

19361931
codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value)
19371932
result = type(self).from_codes(codes, dtype=dtype)
@@ -1969,11 +1964,9 @@ def _tidy_repr(self, max_vals=10, footer=True):
19691964
head = self[:num]._get_repr(length=False, footer=False)
19701965
tail = self[-(max_vals - num) :]._get_repr(length=False, footer=False)
19711966

1972-
result = "{head}, ..., {tail}".format(head=head[:-1], tail=tail[1:])
1967+
result = f"{head[:-1]}, ..., {tail[1:]}"
19731968
if footer:
1974-
result = "{result}\n{footer}".format(
1975-
result=result, footer=self._repr_footer()
1976-
)
1969+
result = f"{result}\n{self._repr_footer()}"
19771970

19781971
return str(result)
19791972

@@ -2007,9 +2000,7 @@ def _repr_categories_info(self):
20072000

20082001
category_strs = self._repr_categories()
20092002
dtype = str(self.categories.dtype)
2010-
levheader = "Categories ({length}, {dtype}): ".format(
2011-
length=len(self.categories), dtype=dtype
2012-
)
2003+
levheader = f"Categories ({len(self.categories)}, {dtype}): "
20132004
width, height = get_terminal_size()
20142005
max_width = get_option("display.width") or width
20152006
if console.in_ipython_frontend():
@@ -2033,10 +2024,8 @@ def _repr_categories_info(self):
20332024
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
20342025

20352026
def _repr_footer(self):
2036-
2037-
return "Length: {length}\n{info}".format(
2038-
length=len(self), info=self._repr_categories_info()
2039-
)
2027+
info = self._repr_categories_info()
2028+
return f"Length: {len(self)}\n{info}"
20402029

20412030
def _get_repr(self, length=True, na_rep="NaN", footer=True):
20422031
from pandas.io.formats import format as fmt
@@ -2058,7 +2047,7 @@ def __repr__(self) -> str:
20582047
result = self._get_repr(length=len(self) > _maxlen)
20592048
else:
20602049
msg = self._get_repr(length=False, footer=True).replace("\n", ", ")
2061-
result = "[], {repr_msg}".format(repr_msg=msg)
2050+
result = f"[], {msg}"
20622051

20632052
return result
20642053

@@ -2189,8 +2178,7 @@ def _reverse_indexer(self):
21892178
def _reduce(self, name, axis=0, **kwargs):
21902179
func = getattr(self, name, None)
21912180
if func is None:
2192-
msg = "Categorical cannot perform the operation {op}"
2193-
raise TypeError(msg.format(op=name))
2181+
raise TypeError(f"Categorical cannot perform the operation {name}")
21942182
return func(**kwargs)
21952183

21962184
def min(self, numeric_only=None, **kwargs):
@@ -2458,11 +2446,10 @@ def isin(self, values):
24582446
array([ True, False, True, False, True, False])
24592447
"""
24602448
if not is_list_like(values):
2449+
values_type = type(values).__name__
24612450
raise TypeError(
24622451
"only list-like objects are allowed to be passed"
2463-
" to isin(), you passed a [{values_type}]".format(
2464-
values_type=type(values).__name__
2465-
)
2452+
f" to isin(), you passed a [{values_type}]"
24662453
)
24672454
values = sanitize_array(values, None, None)
24682455
null_mask = np.asarray(isna(values))

0 commit comments

Comments
 (0)