Skip to content
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

CLN: replace str.format() in pandas/io/formats #30230

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions pandas/io/formats/css.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ def expand(self, prop, value):
try:
mapping = self.SIDE_SHORTHANDS[len(tokens)]
except KeyError:
warnings.warn(
'Could not expand "{prop}: {val}"'.format(prop=prop, val=value),
CSSWarning,
)
warnings.warn(f"Could not expand '{prop}: {value}'", CSSWarning)
return
for key, idx in zip(self.SIDES, mapping):
yield prop_fmt.format(key), tokens[idx]
Expand Down Expand Up @@ -110,14 +107,14 @@ def __call__(self, declarations_str, inherited=None):

# 3. TODO: resolve other font-relative units
for side in self.SIDES:
prop = "border-{side}-width".format(side=side)
prop = f"border-{side}-width"
if prop in props:
props[prop] = self.size_to_pt(
props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS
)
for prop in [
"margin-{side}".format(side=side),
"padding-{side}".format(side=side),
f"margin-{side}",
f"padding-{side}",
]:
if prop in props:
# TODO: support %
Expand Down Expand Up @@ -206,9 +203,9 @@ def _error():

val = round(val, 5)
if int(val) == val:
size_fmt = "{fmt:d}pt".format(fmt=int(val))
size_fmt = f"{int(val):d}pt"
else:
size_fmt = "{fmt:f}pt".format(fmt=val)
size_fmt = f"{val:f}pt"
return size_fmt

def atomize(self, declarations):
Expand Down
18 changes: 8 additions & 10 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,10 @@ def build_border(self, props):
return {
side: {
"style": self._border_style(
props.get("border-{side}-style".format(side=side)),
props.get("border-{side}-width".format(side=side)),
),
"color": self.color_to_excel(
props.get("border-{side}-color".format(side=side))
props.get(f"border-{side}-style"),
props.get(f"border-{side}-width"),
),
"color": self.color_to_excel(props.get(f"border-{side}-color")),
}
for side in ["top", "right", "bottom", "left"]
}
Expand Down Expand Up @@ -427,7 +425,7 @@ def _format_value(self, val):
if missing.isposinf_scalar(val):
val = self.inf_rep
elif missing.isneginf_scalar(val):
val = "-{inf}".format(inf=self.inf_rep)
val = f"-{self.inf_rep}"
elif self.float_format is not None:
val = float(self.float_format % val)
if getattr(val, "tzinfo", None) is not None:
Expand Down Expand Up @@ -509,8 +507,8 @@ def _format_header_regular(self):
if has_aliases:
if len(self.header) != len(self.columns):
raise ValueError(
"Writing {cols} cols but got {alias} "
"aliases".format(cols=len(self.columns), alias=len(self.header))
f"Writing {len(self.columns)} cols but got {len(self.header)} "
"aliases"
)
else:
colnames = self.header
Expand Down Expand Up @@ -718,8 +716,8 @@ def write(
if num_rows > self.max_rows or num_cols > self.max_cols:
raise ValueError(
"This sheet is too large! Your sheet size is: "
+ "{}, {} ".format(num_rows, num_cols)
+ "Max sheet size is: {}, {}".format(self.max_rows, self.max_cols)
+ f"{num_rows}, {num_cols} "
lithomas1 marked this conversation as resolved.
Show resolved Hide resolved
+ f"Max sheet size is: {self.max_rows}, {self.max_cols}"
lithomas1 marked this conversation as resolved.
Show resolved Hide resolved
)

if isinstance(writer, ExcelWriter):
Expand Down
52 changes: 18 additions & 34 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@

jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")


try:
import matplotlib.pyplot as plt
from matplotlib import colors
Expand Down Expand Up @@ -165,7 +164,7 @@ def default_display_func(x):
if self.na_rep is not None and pd.isna(x):
return self.na_rep
elif is_float(x):
display_format = "{0:.{precision}f}".format(x, precision=self.precision)
display_format = f"{x:.{self.precision}f}"
return display_format
else:
return x
Expand Down Expand Up @@ -293,7 +292,7 @@ def format_attr(pair):
name = self.data.columns.names[r]
cs = [
BLANK_CLASS if name is None else INDEX_NAME_CLASS,
"level{lvl}".format(lvl=r),
f"level{r}",
]
name = BLANK_VALUE if name is None else name
row_es.append(
Expand All @@ -310,8 +309,8 @@ def format_attr(pair):
for c, value in enumerate(clabels[r]):
cs = [
COL_HEADING_CLASS,
"level{lvl}".format(lvl=r),
"col{col}".format(col=c),
f"level{r}",
f"col{c}",
]
cs.extend(
cell_context.get("col_headings", {}).get(r, {}).get(c, [])
Expand Down Expand Up @@ -339,7 +338,7 @@ def format_attr(pair):
index_header_row = []

for c, name in enumerate(self.data.index.names):
cs = [INDEX_NAME_CLASS, "level{lvl}".format(lvl=c)]
cs = [INDEX_NAME_CLASS, f"level{c}"]
name = "" if name is None else name
index_header_row.append(
{"type": "th", "value": name, "class": " ".join(cs)}
Expand All @@ -358,8 +357,8 @@ def format_attr(pair):
for c, value in enumerate(rlabels[r]):
rid = [
ROW_HEADING_CLASS,
"level{lvl}".format(lvl=c),
"row{row}".format(row=r),
f"level{c}",
f"row{r}",
]
es = {
"type": "th",
Expand All @@ -377,7 +376,7 @@ def format_attr(pair):
row_es.append(es)

for c, col in enumerate(self.data.columns):
cs = [DATA_CLASS, "row{row}".format(row=r), "col{col}".format(col=c)]
cs = [DATA_CLASS, f"row{r}", f"col{c}"]
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
formatter = self._display_funcs[(r, c)]
value = self.data.iloc[r, c]
Expand All @@ -399,12 +398,7 @@ def format_attr(pair):
props.append(x.split(":"))
else:
props.append(["", ""])
cellstyle.append(
{
"props": props,
"selector": "row{row}_col{col}".format(row=r, col=c),
}
)
cellstyle.append({"props": props, "selector": f"row{r}_col{c}"})
body.append(row_es)

table_attr = self.table_attributes
Expand Down Expand Up @@ -971,9 +965,7 @@ def hide_columns(self, subset):

@staticmethod
def _highlight_null(v, null_color):
return (
"background-color: {color}".format(color=null_color) if pd.isna(v) else ""
)
return f"background-color: {null_color}" if pd.isna(v) else ""

def highlight_null(self, null_color="red"):
"""
Expand Down Expand Up @@ -1126,9 +1118,7 @@ def relative_luminance(rgba):
def css(rgba):
dark = relative_luminance(rgba) < text_color_threshold
text_color = "#f1f1f1" if dark else "#000000"
return "background-color: {b};color: {c};".format(
b=colors.rgb2hex(rgba), c=text_color
)
return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};"

if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
Expand Down Expand Up @@ -1160,7 +1150,7 @@ def set_properties(self, subset=None, **kwargs):
>>> df.style.set_properties(color="white", align="right")
>>> df.style.set_properties(**{'background-color': 'yellow'})
"""
values = ";".join("{p}: {v}".format(p=p, v=v) for p, v in kwargs.items())
values = ";".join(f"{p}: {v}" for p, v in kwargs.items())
f = lambda x: values
return self.applymap(f, subset=subset)

Expand Down Expand Up @@ -1191,12 +1181,9 @@ def css_bar(start, end, color):
if end > start:
css += "background: linear-gradient(90deg,"
if start > 0:
css += " transparent {s:.1f}%, {c} {s:.1f}%, ".format(
s=start, c=color
)
css += "{c} {e:.1f}%, transparent {e:.1f}%)".format(
e=min(end, width), c=color
)
css += f" transparent {start:.1f}%, {color} {start:.1f}%, "
e = min(end, width)
css += f"{color} {e:.1f}%, transparent {e:.1f}%)"
return css

def css(x):
Expand Down Expand Up @@ -1358,7 +1345,7 @@ def _highlight_extrema(data, color="yellow", max_=True):
"""
Highlight the min or max in a Series or DataFrame.
"""
attr = "background-color: {0}".format(color)
attr = f"background-color: {color}"

if max_:
extrema = data == np.nanmax(data.to_numpy())
Expand Down Expand Up @@ -1528,16 +1515,13 @@ def _maybe_wrap_formatter(formatter, na_rep: Optional[str]):
elif callable(formatter):
formatter_func = formatter
else:
msg = (
"Expected a template string or callable, got {formatter} "
"instead".format(formatter=formatter)
)
msg = f"Expected a template string or callable, got {formatter} " "instead"
lithomas1 marked this conversation as resolved.
Show resolved Hide resolved
raise TypeError(msg)

if na_rep is None:
return formatter_func
elif isinstance(na_rep, str):
return lambda x: na_rep if pd.isna(x) else formatter_func(x)
else:
msg = "Expected a string, got {na_rep} instead".format(na_rep=na_rep)
msg = f"Expected a string, got {na_rep} instead"
raise TypeError(msg)