Skip to content

Commit 1486929

Browse files
committed
format replaced with f-strings
1 parent e246c3b commit 1486929

File tree

4 files changed

+27
-40
lines changed

4 files changed

+27
-40
lines changed

pandas/core/groupby/generic.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,7 @@ def _aggregate_multiple_funcs(self, arg, _level):
303303
obj = self
304304
if name in results:
305305
raise SpecificationError(
306-
"Function names must be unique, found multiple named "
307-
"{name}".format(name=name)
306+
f"Function names must be unique, found multiple named {name}"
308307
)
309308

310309
# reset the cache so that we
@@ -396,8 +395,8 @@ def transform(self, func, *args, **kwargs):
396395

397396
if isinstance(func, str):
398397
if not (func in base.transform_kernel_whitelist):
399-
msg = "'{func}' is not a valid function name for transform(name)"
400-
raise ValueError(msg.format(func=func))
398+
msg = f"'{func}' is not a valid function name for transform(name)"
399+
raise ValueError(msg)
401400
if func in base.cythonized_kernels:
402401
# cythonized transform or canned "agg+broadcast"
403402
return getattr(self, func)(*args, **kwargs)
@@ -527,7 +526,7 @@ def nunique(self, dropna: bool = True) -> Series:
527526
try:
528527
sorter = np.lexsort((val, ids))
529528
except TypeError: # catches object dtypes
530-
msg = "val.dtype must be object, got {}".format(val.dtype)
529+
msg = f"val.dtype must be object, got {val.dtype}"
531530
assert val.dtype == object, msg
532531
val, _ = algorithms.factorize(val, sort=False)
533532
sorter = np.lexsort((val, ids))
@@ -1335,8 +1334,8 @@ def transform(self, func, *args, **kwargs):
13351334

13361335
if isinstance(func, str):
13371336
if not (func in base.transform_kernel_whitelist):
1338-
msg = "'{func}' is not a valid function name for transform(name)"
1339-
raise ValueError(msg.format(func=func))
1337+
msg = f"'{func}' is not a valid function name for transform(name)"
1338+
raise ValueError(msg)
13401339
if func in base.cythonized_kernels:
13411340
# cythonized transformation or canned "reduction+broadcast"
13421341
return getattr(self, func)(*args, **kwargs)
@@ -1499,8 +1498,8 @@ def filter(self, func, dropna=True, *args, **kwargs):
14991498
else:
15001499
# non scalars aren't allowed
15011500
raise TypeError(
1502-
"filter function returned a {typ}, "
1503-
"but expected a scalar bool".format(typ=type(res).__name__)
1501+
f"filter function returned a {type(res).__name__}, "
1502+
"but expected a scalar bool"
15041503
)
15051504

15061505
return self._apply_filter(indices, dropna)
@@ -1862,7 +1861,7 @@ def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]:
18621861
for aggfunc in aggfuncs:
18631862
if com.get_callable_name(aggfunc) == "<lambda>":
18641863
aggfunc = partial(aggfunc)
1865-
aggfunc.__name__ = "<lambda_{}>".format(i)
1864+
aggfunc.__name__ = f"<lambda_{i}>"
18661865
i += 1
18671866
mangled_aggfuncs.append(aggfunc)
18681867

pandas/core/groupby/groupby.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -556,9 +556,7 @@ def __getattr__(self, attr):
556556
return self[attr]
557557

558558
raise AttributeError(
559-
"'{typ}' object has no attribute '{attr}'".format(
560-
typ=type(self).__name__, attr=attr
561-
)
559+
f"'{type(self).__name__}' object has no attribute '{attr}'"
562560
)
563561

564562
@Substitution(
@@ -1751,7 +1749,7 @@ def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFra
17511749
raise ValueError(
17521750
"For a DataFrame groupby, dropna must be "
17531751
"either None, 'any' or 'all', "
1754-
"(was passed {dropna}).".format(dropna=dropna)
1752+
f"(was passed {dropna})."
17551753
)
17561754

17571755
# old behaviour, but with all and any support for DataFrames.
@@ -2488,7 +2486,7 @@ def get_groupby(
24882486

24892487
klass = DataFrameGroupBy
24902488
else:
2491-
raise TypeError("invalid type: {obj}".format(obj=obj))
2489+
raise TypeError(f"invalid type: {obj}")
24922490

24932491
return klass(
24942492
obj=obj,

pandas/core/groupby/grouper.py

+11-19
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
174174
else:
175175
if key not in obj._info_axis:
176176
raise KeyError(
177-
"The grouper name {key} is not found".format(key=key)
177+
f"The grouper name {key} is not found"
178178
)
179179
ax = Index(obj[key], name=key)
180180

@@ -192,7 +192,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
192192
else:
193193
if level not in (0, ax.name):
194194
raise ValueError(
195-
"The level {level} is not valid".format(level=level)
195+
f"The level {level} is not valid"
196196
)
197197

198198
# possibly sort
@@ -212,13 +212,13 @@ def groups(self):
212212

213213
def __repr__(self) -> str:
214214
attrs_list = (
215-
"{name}={val!r}".format(name=attr_name, val=getattr(self, attr_name))
215+
f"{attr_name}={getattr(self, attr_name)!r}"
216216
for attr_name in self._attributes
217217
if getattr(self, attr_name) is not None
218218
)
219219
attrs = ", ".join(attrs_list)
220220
cls_name = self.__class__.__name__
221-
return "{cls}({attrs})".format(cls=cls_name, attrs=attrs)
221+
return f"{cls_name}({attrs})"
222222

223223

224224
class Grouping:
@@ -281,7 +281,7 @@ def __init__(
281281
if not isinstance(level, int):
282282
if level not in index.names:
283283
raise AssertionError(
284-
"Level {level} not in index".format(level=level)
284+
f"Level {level} not in index"
285285
)
286286
level = index.names.index(level)
287287

@@ -350,17 +350,15 @@ def __init__(
350350
):
351351
if getattr(self.grouper, "ndim", 1) != 1:
352352
t = self.name or str(type(self.grouper))
353-
raise ValueError("Grouper for '{t}' not 1-dimensional".format(t=t))
353+
raise ValueError(f"Grouper for '{t}' not 1-dimensional")
354354
self.grouper = self.index.map(self.grouper)
355355
if not (
356356
hasattr(self.grouper, "__len__")
357357
and len(self.grouper) == len(self.index)
358358
):
359359
errmsg = (
360360
"Grouper result violates len(labels) == "
361-
"len(data)\nresult: {grper}".format(
362-
grper=pprint_thing(self.grouper)
363-
)
361+
f"len(data)\nresult: {pprint_thing(self.grouper)}"
364362
)
365363
self.grouper = None # Try for sanity
366364
raise AssertionError(errmsg)
@@ -375,7 +373,7 @@ def __init__(
375373
self.grouper = self.grouper.astype("timedelta64[ns]")
376374

377375
def __repr__(self) -> str:
378-
return "Grouping({name})".format(name=self.name)
376+
return f"Grouping({self.name})"
379377

380378
def __iter__(self):
381379
return iter(self.indices)
@@ -501,9 +499,7 @@ def get_grouper(
501499
if isinstance(level, str):
502500
if obj.index.name != level:
503501
raise ValueError(
504-
"level name {level} is not the name of the index".format(
505-
level=level
506-
)
502+
f"level name {level} is not the name of the index"
507503
)
508504
elif level > 0 or level < -1:
509505
raise ValueError("level > 0 or level < -1 only valid with MultiIndex")
@@ -636,12 +632,8 @@ def is_in_obj(gpr) -> bool:
636632

637633
if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]:
638634
raise ValueError(
639-
(
640-
"Length of grouper ({len_gpr}) and axis ({len_axis})"
641-
" must be same length".format(
642-
len_gpr=len(gpr), len_axis=obj.shape[axis]
643-
)
644-
)
635+
f"Length of grouper ({len(gpr)}) and axis ({obj.shape[axis]})"
636+
" must be same length"
645637
)
646638

647639
# create the Grouping

pandas/core/groupby/ops.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -446,17 +446,17 @@ def _cython_operation(
446446
# are not setup for dim transforming
447447
if is_categorical_dtype(values) or is_sparse(values):
448448
raise NotImplementedError(
449-
"{dtype} dtype not supported".format(dtype=values.dtype)
449+
f"{values.dtype} dtype not supported"
450450
)
451451
elif is_datetime64_any_dtype(values):
452452
if how in ["add", "prod", "cumsum", "cumprod"]:
453453
raise NotImplementedError(
454-
"datetime64 type does not support {how} operations".format(how=how)
454+
f"datetime64 type does not support {how} operations"
455455
)
456456
elif is_timedelta64_dtype(values):
457457
if how in ["prod", "cumprod"]:
458458
raise NotImplementedError(
459-
"timedelta64 type does not support {how} operations".format(how=how)
459+
f"timedelta64 type does not support {how} operations"
460460
)
461461

462462
if is_datetime64tz_dtype(values.dtype):
@@ -509,9 +509,7 @@ def _cython_operation(
509509
out_dtype = "float"
510510
else:
511511
if is_numeric:
512-
out_dtype = "{kind}{itemsize}".format(
513-
kind=values.dtype.kind, itemsize=values.dtype.itemsize
514-
)
512+
out_dtype = f"{values.dtype.kind}{values.dtype.itemsize}"
515513
else:
516514
out_dtype = "object"
517515

0 commit comments

Comments
 (0)