Skip to content

CLN: 29547 replace old string formatting #32034

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
22 changes: 10 additions & 12 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,13 @@ def _simple_new(
left = ensure_index(left, copy=copy)
right = ensure_index(right, copy=copy)

if dtype is not None:
if dtype:
# GH 19262: dtype must be an IntervalDtype to override inferred
dtype = pandas_dtype(dtype)
if not is_interval_dtype(dtype):
msg = f"dtype must be an IntervalDtype, got {dtype}"
raise TypeError(msg)
elif dtype.subtype is not None:
elif dtype.subtype:
left = left.astype(dtype.subtype)
right = right.astype(dtype.subtype)

Expand Down Expand Up @@ -637,9 +637,9 @@ def fillna(self, value=None, method=None, limit=None):
-------
filled : IntervalArray with NA/NaN filled
"""
if method is not None:
if method:
raise TypeError("Filling by method is not supported for IntervalArray.")
if limit is not None:
if limit:
raise TypeError("limit is not supported for IntervalArray.")

if not isinstance(value, ABCInterval):
Expand Down Expand Up @@ -1127,8 +1127,8 @@ def __arrow_array__(self, type=None):
subtype = pyarrow.from_numpy_dtype(self.dtype.subtype)
except TypeError:
raise TypeError(
"Conversion to arrow with subtype '{}' "
"is not supported".format(self.dtype.subtype)
f"Conversion to arrow with subtype '{self.dtype.subtype}' "
"is not supported"
)
interval_type = ArrowIntervalType(subtype, self.closed)
storage_array = pyarrow.StructArray.from_arrays(
Expand All @@ -1149,22 +1149,20 @@ def __arrow_array__(self, type=None):
children=[storage_array.field(0), storage_array.field(1)],
)

if type is not None:
if type:
if type.equals(interval_type.storage_type):
return storage_array
elif isinstance(type, ArrowIntervalType):
# ensure we have the same subtype and closed attributes
if not type.equals(interval_type):
raise TypeError(
"Not supported to convert IntervalArray to type with "
"different 'subtype' ({0} vs {1}) and 'closed' ({2} vs {3}) "
"attributes".format(
self.dtype.subtype, type.subtype, self.closed, type.closed
)
f"different 'subtype' ({self.dtype.subtype} vs {type.subtype}) "
f"and 'closed' ({self.closed} vs {type.closed}) attributes"
)
else:
raise TypeError(
"Not supported to convert IntervalArray to '{0}' type".format(type)
f"Not supported to convert IntervalArray to '{type}' type"
)

return pyarrow.ExtensionArray.from_storage(interval_type, storage_array)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/util/hashing.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def hash_array(
elif issubclass(dtype.type, (np.datetime64, np.timedelta64)):
vals = vals.view("i8").astype("u8", copy=False)
elif issubclass(dtype.type, np.number) and dtype.itemsize <= 8:
vals = vals.view("u{}".format(vals.dtype.itemsize)).astype("u8")
vals = vals.view(f"u{vals.dtype.itemsize}").astype("u8")
else:
# With repeated values, its MUCH faster to categorize object dtypes,
# then hash and rename categories. We allow skipping the categorization
Expand Down
61 changes: 24 additions & 37 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def _get_footer(self) -> str:
if self.length:
if footer:
footer += ", "
footer += "Length: {length}".format(length=len(self.categorical))
footer += f"Length: {len(self.categorical)}"

level_info = self.categorical._repr_categories_info()

Expand Down Expand Up @@ -217,7 +217,6 @@ def to_string(self) -> str:

fmt_values = self._get_formatted_values()

fmt_values = ["{i}".format(i=i) for i in fmt_values]
fmt_values = [i.strip() for i in fmt_values]
values = ", ".join(fmt_values)
result = ["[" + values + "]"]
Expand Down Expand Up @@ -301,28 +300,26 @@ def _get_footer(self) -> str:
assert isinstance(
self.series.index, (ABCDatetimeIndex, ABCPeriodIndex, ABCTimedeltaIndex)
)
footer += "Freq: {freq}".format(freq=self.series.index.freqstr)
footer += f"Freq: {self.series.index.freqstr}"

if self.name is not False and name is not None:
if footer:
footer += ", "

series_name = pprint_thing(name, escape_chars=("\t", "\r", "\n"))
footer += (
("Name: {sname}".format(sname=series_name)) if name is not None else ""
)
footer += f"Name: {series_name}"

if self.length is True or (self.length == "truncate" and self.truncate_v):
if footer:
footer += ", "
footer += "Length: {length}".format(length=len(self.series))
footer += f"Length: {len(self.series)}"

if self.dtype is not False and self.dtype is not None:
name = getattr(self.tr_series.dtype, "name", None)
if name:
if footer:
footer += ", "
footer += "dtype: {typ}".format(typ=pprint_thing(name))
footer += f"dtype: {pprint_thing(name)}"

# level infos are added to the end and in a new line, like it is done
# for Categoricals
Expand Down Expand Up @@ -359,9 +356,7 @@ def to_string(self) -> str:
footer = self._get_footer()

if len(series) == 0:
return "{name}([], {footer})".format(
name=type(self.series).__name__, footer=footer
)
return f"{type(self.series).__name__}([], {footer})"

fmt_index, have_header = self._get_formatted_index()
fmt_values = self._get_formatted_values()
Expand Down Expand Up @@ -584,10 +579,8 @@ def __init__(
self.formatters = formatters
else:
raise ValueError(
(
"Formatters length({flen}) should match "
"DataFrame number of columns({dlen})"
).format(flen=len(formatters), dlen=len(frame.columns))
f"Formatters length({len(formatters)}) should match "
f"DataFrame number of columns({len(frame.columns)})"
)
self.na_rep = na_rep
self.decimal = decimal
Expand Down Expand Up @@ -816,10 +809,10 @@ def write_result(self, buf: IO[str]) -> None:
frame = self.frame

if len(frame.columns) == 0 or len(frame.index) == 0:
info_line = "Empty {name}\nColumns: {col}\nIndex: {idx}".format(
name=type(self.frame).__name__,
col=pprint_thing(frame.columns),
idx=pprint_thing(frame.index),
info_line = (
f"Empty {type(self.frame).__name__}\n"
f"Columns: {pprint_thing(frame.columns)}\n"
f"Index: {pprint_thing(frame.index)}"
)
text = info_line
else:
Expand Down Expand Up @@ -865,11 +858,7 @@ def write_result(self, buf: IO[str]) -> None:
buf.writelines(text)

if self.should_show_dimensions:
buf.write(
"\n\n[{nrows} rows x {ncols} columns]".format(
nrows=len(frame), ncols=len(frame.columns)
)
)
buf.write(f"\n\n[{len(frame)} rows x {len(frame.columns)} columns]")

def _join_multiline(self, *args) -> str:
lwidth = self.line_width
Expand Down Expand Up @@ -1074,7 +1063,7 @@ def _get_formatted_index(self, frame: "DataFrame") -> List[str]:

# empty space for columns
if self.show_col_idx_names:
col_header = ["{x}".format(x=x) for x in self._get_column_name_list()]
col_header = [str(x) for x in self._get_column_name_list()]
else:
col_header = [""] * columns.nlevels

Expand Down Expand Up @@ -1209,10 +1198,8 @@ def _format_strings(self) -> List[str]:
if self.float_format is None:
float_format = get_option("display.float_format")
if float_format is None:
fmt_str = "{{x: .{prec:d}g}}".format(
prec=get_option("display.precision")
)
float_format = lambda x: fmt_str.format(x=x)
precision = get_option("display.precision")
float_format = lambda x: f"{x: .{precision:d}g}"
else:
float_format = self.float_format

Expand All @@ -1238,10 +1225,10 @@ def _format(x):
pass
return self.na_rep
elif isinstance(x, PandasObject):
return "{x}".format(x=x)
return str(x)
else:
# object dtype
return "{x}".format(x=formatter(x))
return str(formatter(x))

vals = self.values
if isinstance(vals, Index):
Expand All @@ -1257,7 +1244,7 @@ def _format(x):
fmt_values = []
for i, v in enumerate(vals):
if not is_float_type[i] and leading_space:
fmt_values.append(" {v}".format(v=_format(v)))
fmt_values.append(f" {_format(v)}")
elif is_float_type[i]:
fmt_values.append(float_format(v))
else:
Expand Down Expand Up @@ -1437,7 +1424,7 @@ def _format_strings(self) -> List[str]:

class IntArrayFormatter(GenericArrayFormatter):
def _format_strings(self) -> List[str]:
formatter = self.formatter or (lambda x: "{x: d}".format(x=x))
formatter = self.formatter or (lambda x: f"{x: d}")
fmt_values = [formatter(x) for x in self.values]
return fmt_values

Expand Down Expand Up @@ -1716,7 +1703,7 @@ def _formatter(x):
x = Timedelta(x)
result = x._repr_base(format=format)
if box:
result = "'{res}'".format(res=result)
result = repr(result)
return result

return _formatter
Expand Down Expand Up @@ -1880,16 +1867,16 @@ def __call__(self, num: Union[int, float]) -> str:
prefix = self.ENG_PREFIXES[int_pow10]
else:
if int_pow10 < 0:
prefix = "E-{pow10:02d}".format(pow10=-int_pow10)
prefix = f"E-{-int_pow10:02d}"
else:
prefix = "E+{pow10:02d}".format(pow10=int_pow10)
prefix = f"E+{int_pow10:02d}"

mant = sign * dnum / (10 ** pow10)

if self.accuracy is None: # pragma: no cover
format_str = "{mant: g}{prefix}"
else:
format_str = "{{mant: .{acc:d}f}}{{prefix}}".format(acc=self.accuracy)
format_str = f"{{mant: .{self.accuracy:d}f}}{{prefix}}"

formatted = format_str.format(mant=mant, prefix=prefix)

Expand Down
29 changes: 10 additions & 19 deletions pandas/io/formats/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __init__(
self.table_id = self.fmt.table_id
self.render_links = self.fmt.render_links
if isinstance(self.fmt.col_space, int):
self.fmt.col_space = "{colspace}px".format(colspace=self.fmt.col_space)
self.fmt.col_space = f"{self.fmt.col_space}px"

@property
def show_row_idx_names(self) -> bool:
Expand Down Expand Up @@ -124,7 +124,7 @@ def write_th(
"""
if header and self.fmt.col_space is not None:
tags = tags or ""
tags += 'style="min-width: {colspace};"'.format(colspace=self.fmt.col_space)
tags += f'style="min-width: {self.fmt.col_space};"'

self._write_cell(s, kind="th", indent=indent, tags=tags)

Expand All @@ -135,9 +135,9 @@ def _write_cell(
self, s: Any, kind: str = "td", indent: int = 0, tags: Optional[str] = None
) -> None:
if tags is not None:
start_tag = "<{kind} {tags}>".format(kind=kind, tags=tags)
start_tag = f"<{kind} {tags}>"
else:
start_tag = "<{kind}>".format(kind=kind)
start_tag = f"<{kind}>"

if self.escape:
# escape & first to prevent double escaping of &
Expand All @@ -149,17 +149,12 @@ def _write_cell(

if self.render_links and is_url(rs):
rs_unescaped = pprint_thing(s, escape_chars={}).strip()
start_tag += '<a href="{url}" target="_blank">'.format(url=rs_unescaped)
start_tag += f'<a href="{rs_unescaped}" target="_blank">'
end_a = "</a>"
else:
end_a = ""

self.write(
"{start}{rs}{end_a}</{kind}>".format(
start=start_tag, rs=rs, end_a=end_a, kind=kind
),
indent,
)
self.write(f"{start_tag}{rs}{end_a}</{kind}>", indent)

def write_tr(
self,
Expand All @@ -177,7 +172,7 @@ def write_tr(
if align is None:
self.write("<tr>", indent)
else:
self.write('<tr style="text-align: {align};">'.format(align=align), indent)
self.write(f'<tr style="text-align: {align};">', indent)
indent += indent_delta

for i, s in enumerate(line):
Expand All @@ -196,9 +191,7 @@ def render(self) -> List[str]:
if self.should_show_dimensions:
by = chr(215) # ×
self.write(
"<p>{rows} rows {by} {cols} columns</p>".format(
rows=len(self.frame), by=by, cols=len(self.frame.columns)
)
f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>"
)

return self.elements
Expand All @@ -224,12 +217,10 @@ def _write_table(self, indent: int = 0) -> None:
if self.table_id is None:
id_section = ""
else:
id_section = ' id="{table_id}"'.format(table_id=self.table_id)
id_section = f' id="{self.table_id}"'

self.write(
'<table border="{border}" class="{cls}"{id_section}>'.format(
border=self.border, cls=" ".join(_classes), id_section=id_section
),
f'<table border="{self.border}" class="{" ".join(_classes)}"{id_section}>',
indent,
)

Expand Down
Loading