Skip to content

Commit 75295e1

Browse files
AaronCritchleyjreback
authored andcommitted
CLN: Replacing %s with .format in pandas/core/frame.py (pandas-dev#20461)
1 parent 6245e8c commit 75295e1

File tree

1 file changed

+49
-35
lines changed

1 file changed

+49
-35
lines changed

pandas/core/frame.py

+49-35
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
411411
arr = np.array(data, dtype=dtype, copy=copy)
412412
except (ValueError, TypeError) as e:
413413
exc = TypeError('DataFrame constructor called with '
414-
'incompatible data and dtype: %s' % e)
414+
'incompatible data and dtype: {e}'.format(e=e))
415415
raise_with_traceback(exc)
416416

417417
if arr.ndim == 0 and index is not None and columns is not None:
@@ -520,8 +520,9 @@ def _get_axes(N, K, index=index, columns=columns):
520520
try:
521521
values = values.astype(dtype)
522522
except Exception as orig:
523-
e = ValueError("failed to cast to '%s' (Exception was: %s)"
524-
% (dtype, orig))
523+
e = ValueError("failed to cast to '{dtype}' (Exception "
524+
"was: {orig})".format(dtype=dtype,
525+
orig=orig))
525526
raise_with_traceback(e)
526527

527528
index, columns = _get_axes(*values.shape)
@@ -873,8 +874,9 @@ def dot(self, other):
873874
lvals = self.values
874875
rvals = np.asarray(other)
875876
if lvals.shape[1] != rvals.shape[0]:
876-
raise ValueError('Dot product shape mismatch, %s vs %s' %
877-
(lvals.shape, rvals.shape))
877+
raise ValueError('Dot product shape mismatch, '
878+
'{l} vs {r}'.format(l=lvals.shape,
879+
r=rvals.shape))
878880

879881
if isinstance(other, DataFrame):
880882
return self._constructor(np.dot(lvals, rvals), index=left.index,
@@ -888,7 +890,7 @@ def dot(self, other):
888890
else:
889891
return Series(result, index=left.index)
890892
else: # pragma: no cover
891-
raise TypeError('unsupported type: %s' % type(other))
893+
raise TypeError('unsupported type: {oth}'.format(oth=type(other)))
892894

893895
def __matmul__(self, other):
894896
""" Matrix multiplication using binary `@` operator in Python>=3.5 """
@@ -1098,7 +1100,7 @@ def to_dict(self, orient='dict', into=dict):
10981100
return into_c((t[0], dict(zip(self.columns, t[1:])))
10991101
for t in self.itertuples())
11001102
else:
1101-
raise ValueError("orient '%s' not understood" % orient)
1103+
raise ValueError("orient '{o}' not understood".format(o=orient))
11021104

11031105
def to_gbq(self, destination_table, project_id, chunksize=None,
11041106
verbose=None, reauth=False, if_exists='fail', private_key=None,
@@ -2140,7 +2142,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None,
21402142
lines.append(self.index._summary())
21412143

21422144
if len(self.columns) == 0:
2143-
lines.append('Empty %s' % type(self).__name__)
2145+
lines.append('Empty {name}'.format(name=type(self).__name__))
21442146
fmt.buffer_put_lines(buf, lines)
21452147
return
21462148

@@ -2166,13 +2168,15 @@ def _verbose_repr():
21662168
space = max(len(pprint_thing(k)) for k in self.columns) + 4
21672169
counts = None
21682170

2169-
tmpl = "%s%s"
2171+
tmpl = "{count}{dtype}"
21702172
if show_counts:
21712173
counts = self.count()
21722174
if len(cols) != len(counts): # pragma: no cover
2173-
raise AssertionError('Columns must equal counts (%d != %d)'
2174-
% (len(cols), len(counts)))
2175-
tmpl = "%s non-null %s"
2175+
raise AssertionError(
2176+
'Columns must equal counts '
2177+
'({cols:d} != {counts:d})'.format(
2178+
cols=len(cols), counts=len(counts)))
2179+
tmpl = "{count} non-null {dtype}"
21762180

21772181
dtypes = self.dtypes
21782182
for i, col in enumerate(self.columns):
@@ -2183,7 +2187,8 @@ def _verbose_repr():
21832187
if show_counts:
21842188
count = counts.iloc[i]
21852189

2186-
lines.append(_put_str(col, space) + tmpl % (count, dtype))
2190+
lines.append(_put_str(col, space) + tmpl.format(count=count,
2191+
dtype=dtype))
21872192

21882193
def _non_verbose_repr():
21892194
lines.append(self.columns._summary(name='Columns'))
@@ -2192,9 +2197,12 @@ def _sizeof_fmt(num, size_qualifier):
21922197
# returns size in human readable format
21932198
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
21942199
if num < 1024.0:
2195-
return "%3.1f%s %s" % (num, size_qualifier, x)
2200+
return ("{num:3.1f}{size_q}"
2201+
"{x}".format(num=num, size_q=size_qualifier, x=x))
21962202
num /= 1024.0
2197-
return "%3.1f%s %s" % (num, size_qualifier, 'PB')
2203+
return "{num:3.1f}{size_q} {pb}".format(num=num,
2204+
size_q=size_qualifier,
2205+
pb='PB')
21982206

21992207
if verbose:
22002208
_verbose_repr()
@@ -2207,8 +2215,9 @@ def _sizeof_fmt(num, size_qualifier):
22072215
_verbose_repr()
22082216

22092217
counts = self.get_dtype_counts()
2210-
dtypes = ['%s(%d)' % k for k in sorted(compat.iteritems(counts))]
2211-
lines.append('dtypes: %s' % ', '.join(dtypes))
2218+
dtypes = ['{k}({kk:d})'.format(k=k[0], kk=k[1]) for k
2219+
in sorted(compat.iteritems(counts))]
2220+
lines.append('dtypes: {types}'.format(types=', '.join(dtypes)))
22122221

22132222
if memory_usage is None:
22142223
memory_usage = get_option('display.memory_usage')
@@ -2226,8 +2235,9 @@ def _sizeof_fmt(num, size_qualifier):
22262235
self.index._is_memory_usage_qualified()):
22272236
size_qualifier = '+'
22282237
mem_usage = self.memory_usage(index=True, deep=deep).sum()
2229-
lines.append("memory usage: %s\n" %
2230-
_sizeof_fmt(mem_usage, size_qualifier))
2238+
lines.append("memory usage: {mem}\n".format(
2239+
mem=_sizeof_fmt(mem_usage, size_qualifier)))
2240+
22312241
fmt.buffer_put_lines(buf, lines)
22322242

22332243
def memory_usage(self, index=True, deep=False):
@@ -3013,8 +3023,8 @@ def select_dtypes(self, include=None, exclude=None):
30133023

30143024
# can't both include AND exclude!
30153025
if not include.isdisjoint(exclude):
3016-
raise ValueError('include and exclude overlap on %s' %
3017-
(include & exclude))
3026+
raise ValueError('include and exclude overlap on {inc_ex}'.format(
3027+
inc_ex=(include & exclude)))
30183028

30193029
# empty include/exclude -> defaults to True
30203030
# three cases (we've already raised if both are empty)
@@ -3869,7 +3879,8 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
38693879

38703880
if verify_integrity and not index.is_unique:
38713881
duplicates = index.get_duplicates()
3872-
raise ValueError('Index has duplicate keys: %s' % duplicates)
3882+
raise ValueError('Index has duplicate keys: {dup}'.format(
3883+
dup=duplicates))
38733884

38743885
for c in to_remove:
38753886
del frame[c]
@@ -4241,7 +4252,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
42414252
mask = count > 0
42424253
else:
42434254
if how is not None:
4244-
raise ValueError('invalid how option: %s' % how)
4255+
raise ValueError('invalid how option: {h}'.format(h=how))
42454256
else:
42464257
raise TypeError('must specify how or thresh')
42474258

@@ -6750,8 +6761,8 @@ def _count_level(self, level, axis=0, numeric_only=False):
67506761
agg_axis = frame._get_agg_axis(axis)
67516762

67526763
if not isinstance(count_axis, MultiIndex):
6753-
raise TypeError("Can only count levels on hierarchical %s." %
6754-
self._get_axis_name(axis))
6764+
raise TypeError("Can only count levels on hierarchical "
6765+
"{ax}.".format(ax=self._get_axis_name(axis)))
67556766

67566767
if frame._is_mixed_type:
67576768
# Since we have mixed types, calling notna(frame.values) might
@@ -6829,9 +6840,9 @@ def f(x):
68296840
elif filter_type == 'bool':
68306841
data = self._get_bool_data()
68316842
else: # pragma: no cover
6832-
e = NotImplementedError("Handling exception with filter_"
6833-
"type %s not implemented." %
6834-
filter_type)
6843+
e = NotImplementedError(
6844+
"Handling exception with filter_type {f} not"
6845+
"implemented.".format(f=filter_type))
68356846
raise_with_traceback(e)
68366847
with np.errstate(all='ignore'):
68376848
result = f(data.values)
@@ -6843,8 +6854,8 @@ def f(x):
68436854
elif filter_type == 'bool':
68446855
data = self._get_bool_data()
68456856
else: # pragma: no cover
6846-
msg = ("Generating numeric_only data with filter_type %s"
6847-
"not supported." % filter_type)
6857+
msg = ("Generating numeric_only data with filter_type {f}"
6858+
"not supported.".format(f=filter_type))
68486859
raise NotImplementedError(msg)
68496860
values = data.values
68506861
labels = data._get_agg_axis(axis)
@@ -7119,7 +7130,8 @@ def to_timestamp(self, freq=None, how='start', axis=0, copy=True):
71197130
elif axis == 1:
71207131
new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how))
71217132
else: # pragma: no cover
7122-
raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis))
7133+
raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format(
7134+
ax=axis))
71237135

71247136
return self._constructor(new_data)
71257137

@@ -7150,7 +7162,8 @@ def to_period(self, freq=None, axis=0, copy=True):
71507162
elif axis == 1:
71517163
new_data.set_axis(0, self.columns.to_period(freq=freq))
71527164
else: # pragma: no cover
7153-
raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis))
7165+
raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format(
7166+
ax=axis))
71547167

71557168
return self._constructor(new_data)
71567169

@@ -7509,8 +7522,9 @@ def _convert_object_array(content, columns, coerce_float=False, dtype=None):
75097522
else:
75107523
if len(columns) != len(content): # pragma: no cover
75117524
# caller's responsibility to check for this...
7512-
raise AssertionError('%d columns passed, passed data had %s '
7513-
'columns' % (len(columns), len(content)))
7525+
raise AssertionError('{col:d} columns passed, passed data had '
7526+
'{con} columns'.format(col=len(columns),
7527+
con=len(content)))
75147528

75157529
# provide soft conversion of object dtypes
75167530
def convert(arr):
@@ -7585,4 +7599,4 @@ def _from_nested_dict(data):
75857599

75867600

75877601
def _put_str(s, space):
7588-
return ('%s' % s)[:space].ljust(space)
7602+
return u'{s}'.format(s=s)[:space].ljust(space)

0 commit comments

Comments
 (0)