From dfe67bbd0b6bf6d357cc18200ed3e5e01bc8635a Mon Sep 17 00:00:00 2001 From: tp Date: Wed, 20 Nov 2019 17:31:09 +0000 Subject: [PATCH 1/2] CLN: Convert core.categorical to use f-strings --- pandas/core/arrays/categorical.py | 83 +++++++++++++------------------ 1 file changed, 35 insertions(+), 48 deletions(-) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c6e2a7b7a6e00..3b48dfbc56197 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -73,10 +73,10 @@ def _cat_compare_op(op): - opname = "__{op}__".format(op=op.__name__) + opname = f"__{op.__name__}__" @unpack_zerodim_and_defer(opname) - def f(self, other): + def func(self, other): # On python2, you can usually compare any type to any type, and # Categoricals can be seen as a custom type, but having different # results depending whether categories are the same or not is kind of @@ -137,11 +137,10 @@ def f(self, other): elif opname == "__ne__": return np.repeat(True, len(self)) else: - msg = ( - "Cannot compare a Categorical for op {op} with a " + raise TypeError( + f"Cannot compare a Categorical for op {opname} with a " "scalar, which is not a category." ) - raise TypeError(msg.format(op=opname)) else: # allow categorical vs object dtype array comparisons for equality @@ -149,16 +148,15 @@ def f(self, other): if opname in ["__eq__", "__ne__"]: return getattr(np.array(self), opname)(np.array(other)) - msg = ( - "Cannot compare a Categorical for op {op} with type {typ}." - "\nIf you want to compare values, use 'np.asarray(cat) " - " other'." + raise TypeError( + f"Cannot compare a Categorical for op {opname} with " + f"type {type(other)}.\nIf you want to compare values, " + f"use 'np.asarray(cat) other'." ) - raise TypeError(msg.format(op=opname, typ=type(other))) - f.__name__ = opname + func.__name__ = opname - return f + return func def contains(cat, key, container): @@ -1060,11 +1058,9 @@ def add_categories(self, new_categories, inplace=False): new_categories = [new_categories] already_included = set(new_categories) & set(self.dtype.categories) if len(already_included) != 0: - msg = ( - "new categories must not include old categories: " - "{already_included!s}" + raise ValueError( + f"new categories must not include old categories: {already_included}" ) - raise ValueError(msg.format(already_included=already_included)) new_categories = list(self.dtype.categories) + list(new_categories) new_dtype = CategoricalDtype(new_categories, self.ordered) @@ -1120,8 +1116,7 @@ def remove_categories(self, removals, inplace=False): new_categories = [x for x in new_categories if notna(x)] if len(not_included) != 0: - msg = "removals must all be in old categories: {not_included!s}" - raise ValueError(msg.format(not_included=not_included)) + raise ValueError(f"removals must all be in old categories: {not_included}") return self.set_categories( new_categories, ordered=self.ordered, rename=False, inplace=inplace @@ -1299,9 +1294,8 @@ def shift(self, periods, fill_value=None): fill_value = self.categories.get_loc(fill_value) else: raise ValueError( - "'fill_value={}' is not present " - "in this Categorical's " - "categories".format(fill_value) + f"'fill_value={fill_value}' is not present " + "in this Categorical's categories" ) if periods > 0: codes[:periods] = fill_value @@ -1342,8 +1336,8 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): # for all other cases, raise for now (similarly as what happens in # Series.__array_prepare__) raise TypeError( - "Object with dtype {dtype} cannot perform " - "the numpy op {op}".format(dtype=self.dtype, op=ufunc.__name__) + f"Object with dtype {self.dtype} cannot perform " + f"the numpy op {ufunc.__name__}" ) def __setstate__(self, state): @@ -1542,9 +1536,9 @@ def check_for_ordered(self, op): """ assert that we are ordered """ if not self.ordered: raise TypeError( - "Categorical is not ordered for operation {op}\n" + f"Categorical is not ordered for operation {op}\n" "you can use .as_ordered() to change the " - "Categorical to an ordered one\n".format(op=op) + "Categorical to an ordered one\n" ) def _values_for_argsort(self): @@ -1679,8 +1673,7 @@ def sort_values(self, inplace=False, ascending=True, na_position="last"): """ inplace = validate_bool_kwarg(inplace, "inplace") if na_position not in ["last", "first"]: - msg = "invalid na_position: {na_position!r}" - raise ValueError(msg.format(na_position=na_position)) + raise ValueError(f"invalid na_position: {na_position!r}") sorted_idx = nargsort(self, ascending=ascending, na_position=na_position) @@ -1836,8 +1829,7 @@ def fillna(self, value=None, method=None, limit=None): else: raise TypeError( '"value" parameter must be a scalar, dict ' - "or Series, but you passed a " - '"{0}"'.format(type(value).__name__) + f'or Series, but you passed a {type(value).__name__!r}"' ) return self._constructor(codes, dtype=self.dtype, fastpath=True) @@ -1930,8 +1922,11 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None): if fill_value in self.categories: fill_value = self.categories.get_loc(fill_value) else: - msg = "'fill_value' ('{}') is not in this Categorical's categories." - raise TypeError(msg.format(fill_value)) + msg = ( + f"'fill_value' ('{fill_value}') is not in this " + "Categorical's categories." + ) + raise TypeError(msg) codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value) result = type(self).from_codes(codes, dtype=dtype) @@ -1969,11 +1964,9 @@ def _tidy_repr(self, max_vals=10, footer=True): head = self[:num]._get_repr(length=False, footer=False) tail = self[-(max_vals - num) :]._get_repr(length=False, footer=False) - result = "{head}, ..., {tail}".format(head=head[:-1], tail=tail[1:]) + result = f"{head[:-1]}, ..., {tail[1:]}" if footer: - result = "{result}\n{footer}".format( - result=result, footer=self._repr_footer() - ) + result = f"{result}\n{self._repr_footer()}" return str(result) @@ -2007,9 +2000,7 @@ def _repr_categories_info(self): category_strs = self._repr_categories() dtype = str(self.categories.dtype) - levheader = "Categories ({length}, {dtype}): ".format( - length=len(self.categories), dtype=dtype - ) + levheader = f"Categories ({len(self.categories)}, {dtype}): " width, height = get_terminal_size() max_width = get_option("display.width") or width if console.in_ipython_frontend(): @@ -2033,10 +2024,8 @@ def _repr_categories_info(self): return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]" def _repr_footer(self): - - return "Length: {length}\n{info}".format( - length=len(self), info=self._repr_categories_info() - ) + info = self._repr_categories_info() + return f"Length: {len(self)}\n{info}" def _get_repr(self, length=True, na_rep="NaN", footer=True): from pandas.io.formats import format as fmt @@ -2058,7 +2047,7 @@ def __repr__(self) -> str: result = self._get_repr(length=len(self) > _maxlen) else: msg = self._get_repr(length=False, footer=True).replace("\n", ", ") - result = "[], {repr_msg}".format(repr_msg=msg) + result = f"[], {msg}" return result @@ -2189,8 +2178,7 @@ def _reverse_indexer(self): def _reduce(self, name, axis=0, **kwargs): func = getattr(self, name, None) if func is None: - msg = "Categorical cannot perform the operation {op}" - raise TypeError(msg.format(op=name)) + raise TypeError(f"Categorical cannot perform the operation {name}") return func(**kwargs) def min(self, numeric_only=None, **kwargs): @@ -2458,11 +2446,10 @@ def isin(self, values): array([ True, False, True, False, True, False]) """ if not is_list_like(values): + values_type = type(values).__name__ raise TypeError( "only list-like objects are allowed to be passed" - " to isin(), you passed a [{values_type}]".format( - values_type=type(values).__name__ - ) + f" to isin(), you passed a [{values_type}]" ) values = sanitize_array(values, None, None) null_mask = np.asarray(isna(values)) From f5f0373971802a92ac35b39dde9e128b9ac6301e Mon Sep 17 00:00:00 2001 From: tp Date: Thu, 21 Nov 2019 02:41:54 +0000 Subject: [PATCH 2/2] remove f from string --- pandas/core/arrays/categorical.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 3b48dfbc56197..9a94345a769df 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -151,7 +151,7 @@ def func(self, other): raise TypeError( f"Cannot compare a Categorical for op {opname} with " f"type {type(other)}.\nIf you want to compare values, " - f"use 'np.asarray(cat) other'." + "use 'np.asarray(cat) other'." ) func.__name__ = opname