Skip to content

Commit d45e12b

Browse files
jschendeljorisvandenbossche
authored andcommitted
CLN: replace %s syntax with .format in missing.py, nanops.py, ops.py (#17322)
Replaced %s syntax with .format in missing.py, nanops.py, ops.py. Additionally, made some of the existing positional .format code more explicit.
1 parent 66ec5f3 commit d45e12b

File tree

3 files changed

+76
-57
lines changed

3 files changed

+76
-57
lines changed

pandas/core/missing.py

+26-15
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ def clean_fill_method(method, allow_nearest=False):
8888
valid_methods.append('nearest')
8989
expecting = 'pad (ffill), backfill (bfill) or nearest'
9090
if method not in valid_methods:
91-
msg = ('Invalid fill method. Expecting %s. Got %s' %
92-
(expecting, method))
91+
msg = ('Invalid fill method. Expecting {expecting}. Got {method}'
92+
.format(expecting=expecting, method=method))
9393
raise ValueError(msg)
9494
return method
9595

@@ -104,8 +104,8 @@ def clean_interp_method(method, **kwargs):
104104
raise ValueError("You must specify the order of the spline or "
105105
"polynomial.")
106106
if method not in valid:
107-
raise ValueError("method must be one of {0}."
108-
"Got '{1}' instead.".format(valid, method))
107+
raise ValueError("method must be one of {valid}. Got '{method}' "
108+
"instead.".format(valid=valid, method=method))
109109

110110
return method
111111

@@ -146,8 +146,10 @@ def interpolate_1d(xvalues, yvalues, method='linear', limit=None,
146146
valid_limit_directions = ['forward', 'backward', 'both']
147147
limit_direction = limit_direction.lower()
148148
if limit_direction not in valid_limit_directions:
149-
raise ValueError('Invalid limit_direction: expecting one of %r, got '
150-
'%r.' % (valid_limit_directions, limit_direction))
149+
msg = ('Invalid limit_direction: expecting one of {valid!r}, '
150+
'got {invalid!r}.')
151+
raise ValueError(msg.format(valid=valid_limit_directions,
152+
invalid=limit_direction))
151153

152154
from pandas import Series
153155
ys = Series(yvalues)
@@ -248,7 +250,8 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
248250
# TODO: Why is DatetimeIndex being imported here?
249251
from pandas import DatetimeIndex # noqa
250252
except ImportError:
251-
raise ImportError('{0} interpolation requires Scipy'.format(method))
253+
raise ImportError('{method} interpolation requires SciPy'
254+
.format(method=method))
252255

253256
new_x = np.asarray(new_x)
254257

@@ -466,7 +469,8 @@ def pad_1d(values, limit=None, mask=None, dtype=None):
466469
dtype = values.dtype
467470
_method = None
468471
if is_float_dtype(values):
469-
_method = getattr(algos, 'pad_inplace_%s' % dtype.name, None)
472+
name = 'pad_inplace_{name}'.format(name=dtype.name)
473+
_method = getattr(algos, name, None)
470474
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
471475
_method = _pad_1d_datetime
472476
elif is_integer_dtype(values):
@@ -476,7 +480,8 @@ def pad_1d(values, limit=None, mask=None, dtype=None):
476480
_method = algos.pad_inplace_object
477481

478482
if _method is None:
479-
raise ValueError('Invalid dtype for pad_1d [%s]' % dtype.name)
483+
raise ValueError('Invalid dtype for pad_1d [{name}]'
484+
.format(name=dtype.name))
480485

481486
if mask is None:
482487
mask = isna(values)
@@ -490,7 +495,8 @@ def backfill_1d(values, limit=None, mask=None, dtype=None):
490495
dtype = values.dtype
491496
_method = None
492497
if is_float_dtype(values):
493-
_method = getattr(algos, 'backfill_inplace_%s' % dtype.name, None)
498+
name = 'backfill_inplace_{name}'.format(name=dtype.name)
499+
_method = getattr(algos, name, None)
494500
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
495501
_method = _backfill_1d_datetime
496502
elif is_integer_dtype(values):
@@ -500,7 +506,8 @@ def backfill_1d(values, limit=None, mask=None, dtype=None):
500506
_method = algos.backfill_inplace_object
501507

502508
if _method is None:
503-
raise ValueError('Invalid dtype for backfill_1d [%s]' % dtype.name)
509+
raise ValueError('Invalid dtype for backfill_1d [{name}]'
510+
.format(name=dtype.name))
504511

505512
if mask is None:
506513
mask = isna(values)
@@ -515,7 +522,8 @@ def pad_2d(values, limit=None, mask=None, dtype=None):
515522
dtype = values.dtype
516523
_method = None
517524
if is_float_dtype(values):
518-
_method = getattr(algos, 'pad_2d_inplace_%s' % dtype.name, None)
525+
name = 'pad_2d_inplace_{name}'.format(name=dtype.name)
526+
_method = getattr(algos, name, None)
519527
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
520528
_method = _pad_2d_datetime
521529
elif is_integer_dtype(values):
@@ -525,7 +533,8 @@ def pad_2d(values, limit=None, mask=None, dtype=None):
525533
_method = algos.pad_2d_inplace_object
526534

527535
if _method is None:
528-
raise ValueError('Invalid dtype for pad_2d [%s]' % dtype.name)
536+
raise ValueError('Invalid dtype for pad_2d [{name}]'
537+
.format(name=dtype.name))
529538

530539
if mask is None:
531540
mask = isna(values)
@@ -544,7 +553,8 @@ def backfill_2d(values, limit=None, mask=None, dtype=None):
544553
dtype = values.dtype
545554
_method = None
546555
if is_float_dtype(values):
547-
_method = getattr(algos, 'backfill_2d_inplace_%s' % dtype.name, None)
556+
name = 'backfill_2d_inplace_{name}'.format(name=dtype.name)
557+
_method = getattr(algos, name, None)
548558
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
549559
_method = _backfill_2d_datetime
550560
elif is_integer_dtype(values):
@@ -554,7 +564,8 @@ def backfill_2d(values, limit=None, mask=None, dtype=None):
554564
_method = algos.backfill_2d_inplace_object
555565

556566
if _method is None:
557-
raise ValueError('Invalid dtype for backfill_2d [%s]' % dtype.name)
567+
raise ValueError('Invalid dtype for backfill_2d [{name}]'
568+
.format(name=dtype.name))
558569

559570
if mask is None:
560571
mask = isna(values)

pandas/core/nanops.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,8 @@ def __call__(self, f):
7070
def _f(*args, **kwargs):
7171
obj_iter = itertools.chain(args, compat.itervalues(kwargs))
7272
if any(self.check(obj) for obj in obj_iter):
73-
raise TypeError('reduction operation {0!r} not allowed for '
74-
'this dtype'.format(
75-
f.__name__.replace('nan', '')))
73+
msg = 'reduction operation {name!r} not allowed for this dtype'
74+
raise TypeError(msg.format(name=f.__name__.replace('nan', '')))
7675
try:
7776
with np.errstate(invalid='ignore'):
7877
return f(*args, **kwargs)
@@ -786,7 +785,8 @@ def _ensure_numeric(x):
786785
try:
787786
x = complex(x)
788787
except Exception:
789-
raise TypeError('Could not convert %s to numeric' % str(x))
788+
raise TypeError('Could not convert {value!s} to numeric'
789+
.format(value=x))
790790
return x
791791

792792
# NA-friendly array comparisons

pandas/core/ops.py

+46-38
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ def _create_methods(arith_method, comp_method, bool_method,
6363

6464
def names(x):
6565
if x[-1] == "_":
66-
return "__%s_" % x
66+
return "__{name}_".format(name=x)
6767
else:
68-
return "__%s__" % x
68+
return "__{name}__".format(name=x)
6969
else:
7070
names = lambda x: x
7171

@@ -388,8 +388,8 @@ def _validate(self, lvalues, rvalues, name):
388388
if name not in ('__div__', '__truediv__', '__mul__', '__rmul__'):
389389
raise TypeError("can only operate on a timedelta and an "
390390
"integer or a float for division and "
391-
"multiplication, but the operator [%s] was"
392-
"passed" % name)
391+
"multiplication, but the operator [{name}] "
392+
"was passed".format(name=name))
393393

394394
# 2 timedeltas
395395
elif ((self.is_timedelta_lhs and
@@ -400,9 +400,9 @@ def _validate(self, lvalues, rvalues, name):
400400
if name not in ('__div__', '__rdiv__', '__truediv__',
401401
'__rtruediv__', '__add__', '__radd__', '__sub__',
402402
'__rsub__'):
403-
raise TypeError("can only operate on a timedeltas for "
404-
"addition, subtraction, and division, but the"
405-
" operator [%s] was passed" % name)
403+
raise TypeError("can only operate on a timedeltas for addition"
404+
", subtraction, and division, but the operator"
405+
" [{name}] was passed".format(name=name))
406406

407407
# datetime and timedelta/DateOffset
408408
elif (self.is_datetime_lhs and
@@ -411,23 +411,24 @@ def _validate(self, lvalues, rvalues, name):
411411
if name not in ('__add__', '__radd__', '__sub__'):
412412
raise TypeError("can only operate on a datetime with a rhs of "
413413
"a timedelta/DateOffset for addition and "
414-
"subtraction, but the operator [%s] was "
415-
"passed" % name)
414+
"subtraction, but the operator [{name}] was "
415+
"passed".format(name=name))
416416

417417
elif (self.is_datetime_rhs and
418418
(self.is_timedelta_lhs or self.is_offset_lhs)):
419419
if name not in ('__add__', '__radd__', '__rsub__'):
420420
raise TypeError("can only operate on a timedelta/DateOffset "
421421
"with a rhs of a datetime for addition, "
422-
"but the operator [%s] was passed" % name)
422+
"but the operator [{name}] was passed"
423+
.format(name=name))
423424

424425
# 2 datetimes
425426
elif self.is_datetime_lhs and self.is_datetime_rhs:
426427

427428
if name not in ('__sub__', '__rsub__'):
428429
raise TypeError("can only operate on a datetimes for"
429-
" subtraction, but the operator [%s] was"
430-
" passed" % name)
430+
" subtraction, but the operator [{name}] was"
431+
" passed".format(name=name))
431432

432433
# if tz's must be equal (same or None)
433434
if getattr(lvalues, 'tz', None) != getattr(rvalues, 'tz', None):
@@ -439,8 +440,8 @@ def _validate(self, lvalues, rvalues, name):
439440

440441
if name not in ('__add__', '__radd__'):
441442
raise TypeError("can only operate on a timedelta/DateOffset "
442-
"and a datetime for addition, but the "
443-
"operator [%s] was passed" % name)
443+
"and a datetime for addition, but the operator"
444+
" [{name}] was passed".format(name=name))
444445
else:
445446
raise TypeError('cannot operate on a series without a rhs '
446447
'of a series/ndarray of type datetime64[ns] '
@@ -498,7 +499,7 @@ def _convert_to_array(self, values, name=None, other=None):
498499
values = values.to_timestamp().to_series()
499500
elif name not in ('__truediv__', '__div__', '__mul__', '__rmul__'):
500501
raise TypeError("incompatible type for a datetime/timedelta "
501-
"operation [{0}]".format(name))
502+
"operation [{name}]".format(name=name))
502503
elif inferred_type == 'floating':
503504
if (isna(values).all() and
504505
name in ('__add__', '__radd__', '__sub__', '__rsub__')):
@@ -508,8 +509,9 @@ def _convert_to_array(self, values, name=None, other=None):
508509
elif self._is_offset(values):
509510
return values
510511
else:
511-
raise TypeError("incompatible type [{0}] for a datetime/timedelta"
512-
" operation".format(np.array(values).dtype))
512+
raise TypeError("incompatible type [{dtype}] for a "
513+
"datetime/timedelta operation"
514+
.format(dtype=np.array(values).dtype))
513515

514516
return values
515517

@@ -866,8 +868,8 @@ def wrapper(self, other, axis=None):
866868
with np.errstate(all='ignore'):
867869
res = na_op(values, other)
868870
if is_scalar(res):
869-
raise TypeError('Could not compare %s type with Series' %
870-
type(other))
871+
raise TypeError('Could not compare {typ} type with Series'
872+
.format(typ=type(other)))
871873

872874
# always return a full value series here
873875
res = _values_from_object(res)
@@ -906,9 +908,10 @@ def na_op(x, y):
906908
y = bool(y)
907909
result = lib.scalar_binop(x, y, op)
908910
except:
909-
raise TypeError("cannot compare a dtyped [{0}] array with "
910-
"a scalar of type [{1}]".format(
911-
x.dtype, type(y).__name__))
911+
msg = ("cannot compare a dtyped [{dtype}] array "
912+
"with a scalar of type [{type}]"
913+
).format(dtype=x.dtype, type=type(y).__name__)
914+
raise TypeError(msg)
912915

913916
return result
914917

@@ -1140,14 +1143,17 @@ def _align_method_FRAME(left, right, axis):
11401143
""" convert rhs to meet lhs dims if input is list, tuple or np.ndarray """
11411144

11421145
def to_series(right):
1143-
msg = 'Unable to coerce to Series, length must be {0}: given {1}'
1146+
msg = ('Unable to coerce to Series, length must be {req_len}: '
1147+
'given {given_len}')
11441148
if axis is not None and left._get_axis_name(axis) == 'index':
11451149
if len(left.index) != len(right):
1146-
raise ValueError(msg.format(len(left.index), len(right)))
1150+
raise ValueError(msg.format(req_len=len(left.index),
1151+
given_len=len(right)))
11471152
right = left._constructor_sliced(right, index=left.index)
11481153
else:
11491154
if len(left.columns) != len(right):
1150-
raise ValueError(msg.format(len(left.columns), len(right)))
1155+
raise ValueError(msg.format(req_len=len(left.columns),
1156+
given_len=len(right)))
11511157
right = left._constructor_sliced(right, index=left.columns)
11521158
return right
11531159

@@ -1161,15 +1167,16 @@ def to_series(right):
11611167

11621168
elif right.ndim == 2:
11631169
if left.shape != right.shape:
1164-
msg = ("Unable to coerce to DataFrame, "
1165-
"shape must be {0}: given {1}")
1166-
raise ValueError(msg.format(left.shape, right.shape))
1170+
msg = ("Unable to coerce to DataFrame, shape "
1171+
"must be {req_shape}: given {given_shape}"
1172+
).format(req_shape=left.shape, given_shape=right.shape)
1173+
raise ValueError(msg)
11671174

11681175
right = left._constructor(right, index=left.index,
11691176
columns=left.columns)
11701177
else:
1171-
msg = 'Unable to coerce to Series/DataFrame, dim must be <= 2: {0}'
1172-
raise ValueError(msg.format(right.shape, ))
1178+
raise ValueError('Unable to coerce to Series/DataFrame, dim '
1179+
'must be <= 2: {dim}'.format(dim=right.shape))
11731180

11741181
return right
11751182

@@ -1278,7 +1285,8 @@ def na_op(x, y):
12781285

12791286
return result
12801287

1281-
@Appender('Wrapper for flexible comparison methods %s' % name)
1288+
@Appender('Wrapper for flexible comparison methods {name}'
1289+
.format(name=name))
12821290
def f(self, other, axis=default_axis, level=None):
12831291

12841292
other = _align_method_FRAME(self, other, axis)
@@ -1299,7 +1307,7 @@ def f(self, other, axis=default_axis, level=None):
12991307

13001308

13011309
def _comp_method_FRAME(func, name, str_rep, masker=False):
1302-
@Appender('Wrapper for comparison method %s' % name)
1310+
@Appender('Wrapper for comparison method {name}'.format(name=name))
13031311
def f(self, other):
13041312
if isinstance(other, pd.DataFrame): # Another DataFrame
13051313
return self._compare_frame(other, func, str_rep)
@@ -1349,9 +1357,9 @@ def na_op(x, y):
13491357
# work only for scalars
13501358
def f(self, other):
13511359
if not is_scalar(other):
1352-
raise ValueError('Simple arithmetic with %s can only be '
1353-
'done with scalar values' %
1354-
self._constructor.__name__)
1360+
raise ValueError('Simple arithmetic with {name} can only be '
1361+
'done with scalar values'
1362+
.format(name=self._constructor.__name__))
13551363

13561364
return self._combine(other, op)
13571365

@@ -1384,7 +1392,7 @@ def na_op(x, y):
13841392

13851393
return result
13861394

1387-
@Appender('Wrapper for comparison method %s' % name)
1395+
@Appender('Wrapper for comparison method {name}'.format(name=name))
13881396
def f(self, other, axis=None):
13891397
# Validate the axis parameter
13901398
if axis is not None:
@@ -1394,8 +1402,8 @@ def f(self, other, axis=None):
13941402
return self._compare_constructor(other, na_op, try_cast=False)
13951403
elif isinstance(other, (self._constructor_sliced, pd.DataFrame,
13961404
ABCSeries)):
1397-
raise Exception("input needs alignment for this object [%s]" %
1398-
self._constructor)
1405+
raise Exception("input needs alignment for this object [{object}]"
1406+
.format(object=self._constructor))
13991407
else:
14001408
return self._combine_const(other, na_op, try_cast=False)
14011409

0 commit comments

Comments
 (0)