Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Feb 3, 2025
1 parent abf7984 commit 581a561
Show file tree
Hide file tree
Showing 83 changed files with 147 additions and 242 deletions.
4 changes: 2 additions & 2 deletions asv_bench/benchmarks/io/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class Render:
def setup(self, cols, rows):
self.df = DataFrame(
np.random.randn(rows, cols),
columns=[f"float_{i+1}" for i in range(cols)],
index=[f"row_{i+1}" for i in range(rows)],
columns=[f"float_{i + 1}" for i in range(cols)],
index=[f"row_{i + 1}" for i in range(rows)],
)

def time_apply_render(self, cols, rows):
Expand Down
6 changes: 2 additions & 4 deletions doc/make.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,7 @@ def latex(self, force=False):
for i in range(3):
self._run_os("pdflatex", "-interaction=nonstopmode", "pandas.tex")
raise SystemExit(
"You should check the file "
'"build/latex/pandas.pdf" for problems.'
'You should check the file "build/latex/pandas.pdf" for problems.'
)
self._run_os("make")
return ret_code
Expand Down Expand Up @@ -343,8 +342,7 @@ def main():
dest="verbosity",
default=0,
help=(
"increase verbosity (can be repeated), "
"passed to the sphinx build command"
"increase verbosity (can be repeated), passed to the sphinx build command"
),
)
argparser.add_argument(
Expand Down
2 changes: 1 addition & 1 deletion doc/source/user_guide/style.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1288,7 +1288,7 @@
"outputs": [],
"source": [
"df2.loc[:4].style.highlight_max(\n",
" axis=1, props=(\"color:white; \" \"font-weight:bold; \" \"background-color:darkblue;\")\n",
" axis=1, props=(\"color:white; font-weight:bold; background-color:darkblue;\")\n",
")"
]
},
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1645,8 +1645,7 @@ def reconstruct_func(
# GH 28426 will raise error if duplicated function names are used and
# there is no reassigned name
raise SpecificationError(
"Function names must be unique if there is no new column names "
"assigned"
"Function names must be unique if there is no new column names assigned"
)
if func is None:
# nicer error message
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1791,7 +1791,9 @@ def take(self, indices, allow_fill=False, fill_value=None):
# type for the array, to the physical storage type for
# the data, before passing to take.
result = take(data, indices, fill_value=fill_value, allow_fill=allow_fill)
result = take(
data, indices, fill_value=fill_value, allow_fill=allow_fill
)
return self._from_sequence(result, dtype=self.dtype)
""" # noqa: E501
# Implementer note: The `fill_value` parameter should be a user-facing
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2707,8 +2707,7 @@ def _maybe_infer_tz(tz: tzinfo | None, inferred_tz: tzinfo | None) -> tzinfo | N
pass
elif not timezones.tz_compare(tz, inferred_tz):
raise TypeError(
f"data is already tz-aware {inferred_tz}, unable to "
f"set specified tz: {tz}"
f"data is already tz-aware {inferred_tz}, unable to set specified tz: {tz}"
)
return tz

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ def visit_Call(self, node, side=None, **kwargs):
if not isinstance(key, ast.keyword):
# error: "expr" has no attribute "id"
raise ValueError(
"keyword error in function call " f"'{node.func.id}'" # type: ignore[attr-defined]
f"keyword error in function call '{node.func.id}'" # type: ignore[attr-defined]
)

if key.arg:
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,8 +512,7 @@ def __init__(self, op: Literal["+", "-", "~", "not"], operand) -> None:
self.func = _unary_ops_dict[op]
except KeyError as err:
raise ValueError(
f"Invalid unary operator {op!r}, "
f"valid operators are {UNARY_OPS_SYMS}"
f"Invalid unary operator {op!r}, valid operators are {UNARY_OPS_SYMS}"
) from err

def __call__(self, env) -> MathCall:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,7 @@ def maybe_cast_to_integer_array(arr: list | np.ndarray, dtype: np.dtype) -> np.n
# (test_constructor_coercion_signed_to_unsigned) so safe to ignore.
warnings.filterwarnings(
"ignore",
"NumPy will stop allowing conversion of " "out-of-bound Python int",
"NumPy will stop allowing conversion of out-of-bound Python int",
DeprecationWarning,
)
casted = np.asarray(arr, dtype=dtype)
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,8 +605,7 @@ def update_dtype(self, dtype: str_type | CategoricalDtype) -> CategoricalDtype:
return self
elif not self.is_dtype(dtype):
raise ValueError(
f"a CategoricalDtype must be passed to perform an update, "
f"got {dtype!r}"
f"a CategoricalDtype must be passed to perform an update, got {dtype!r}"
)
else:
# from here on, dtype is a CategoricalDtype
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5537,8 +5537,7 @@ def filter(
nkw = common.count_not_none(items, like, regex)
if nkw > 1:
raise TypeError(
"Keyword arguments `items`, `like`, or `regex` "
"are mutually exclusive"
"Keyword arguments `items`, `like`, or `regex` are mutually exclusive"
)

if axis is None:
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2625,8 +2625,7 @@ def _value_counts(
doesnt_exist = subsetted - unique_cols
if doesnt_exist:
raise ValueError(
f"Keys {doesnt_exist} in subset do not "
f"exist in the DataFrame."
f"Keys {doesnt_exist} in subset do not exist in the DataFrame."
)
else:
subsetted = unique_cols
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,8 +516,7 @@ def __init__(
):
grper = pprint_thing(grouping_vector)
errmsg = (
"Grouper result violates len(labels) == "
f"len(data)\nresult: {grper}"
f"Grouper result violates len(labels) == len(data)\nresult: {grper}"
)
raise AssertionError(errmsg)

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexers/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,9 +478,9 @@ def get_window_bounds(
)
start = start.astype(np.int64)
end = end.astype(np.int64)
assert len(start) == len(
end
), "these should be equal in length from get_window_bounds"
assert len(start) == len(end), (
"these should be equal in length from get_window_bounds"
)
# Cannot use groupby_indices as they might not be monotonic with the object
# we're rolling over
window_indices = np.arange(
Expand Down
12 changes: 4 additions & 8 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,8 +975,7 @@ def _validate_tuple_indexer(self, key: tuple) -> tuple:
self._validate_key(k, i)
except ValueError as err:
raise ValueError(
"Location based indexing can only have "
f"[{self._valid_types}] types"
f"Location based indexing can only have [{self._valid_types}] types"
) from err
return key

Expand Down Expand Up @@ -1589,8 +1588,7 @@ def _validate_key(self, key, axis: AxisInt) -> None:
"is not available"
)
raise ValueError(
"iLocation based boolean indexing cannot use "
"an indexable as a mask"
"iLocation based boolean indexing cannot use an indexable as a mask"
)
return

Expand Down Expand Up @@ -1994,8 +1992,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
return self._setitem_with_indexer((pi, info_axis[0]), value[0])

raise ValueError(
"Must have equal len keys and value "
"when setting with an iterable"
"Must have equal len keys and value when setting with an iterable"
)

elif lplane_indexer == 0 and len(value) == len(self.obj.index):
Expand Down Expand Up @@ -2023,8 +2020,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):

else:
raise ValueError(
"Must have equal len keys and value "
"when setting with an iterable"
"Must have equal len keys and value when setting with an iterable"
)

else:
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/interchange/buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ def __init__(self, x: np.ndarray, allow_copy: bool = True) -> None:
x = x.copy()
else:
raise RuntimeError(
"Exports cannot be zero-copy in the case "
"of a non-contiguous buffer"
"Exports cannot be zero-copy in the case of a non-contiguous buffer"
)

# Store the numpy array in which the data resides as a private
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2264,8 +2264,7 @@ def check_ndim(values, placement: BlockPlacement, ndim: int) -> None:
if values.ndim > ndim:
# Check for both np.ndarray and ExtensionArray
raise ValueError(
"Wrong number of dimensions. "
f"values.ndim > ndim [{values.ndim} > {ndim}]"
f"Wrong number of dimensions. values.ndim > ndim [{values.ndim} > {ndim}]"
)

if not is_1d_only_ea_dtype(values.dtype):
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -907,8 +907,7 @@ def _validate_or_indexify_columns(
if not is_mi_list and len(columns) != len(content): # pragma: no cover
# caller's responsibility to check for this...
raise AssertionError(
f"{len(columns)} columns passed, passed data had "
f"{len(content)} columns"
f"{len(columns)} columns passed, passed data had {len(content)} columns"
)
if is_mi_list:
# check if nested list column, length of each sub-list should be equal
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/ops/array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _masked_arith_op(x: np.ndarray, y, op) -> np.ndarray:
else:
if not is_scalar(y):
raise TypeError(
f"Cannot broadcast np.ndarray with operand of type { type(y) }"
f"Cannot broadcast np.ndarray with operand of type {type(y)}"
)

# mask is only meaningful for x
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/reshape/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,7 @@ def from_dummies(

if col_isna_mask.any():
raise ValueError(
"Dummy DataFrame contains NA value in column: "
f"'{col_isna_mask.idxmax()}'"
f"Dummy DataFrame contains NA value in column: '{col_isna_mask.idxmax()}'"
)

# index data with a list of all columns that are dummies
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1929,9 +1929,9 @@ def get_join_indexers(
np.ndarray[np.intp] or None
Indexer into the right_keys.
"""
assert len(left_keys) == len(
right_keys
), "left_keys and right_keys must be the same length"
assert len(left_keys) == len(right_keys), (
"left_keys and right_keys must be the same length"
)

# fast-path for empty left/right
left_n = len(left_keys[0])
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ def should_cache(
else:
check_count = 500
else:
assert (
0 <= check_count <= len(arg)
), "check_count must be in next bounds: [0; len(arg)]"
assert 0 <= check_count <= len(arg), (
"check_count must be in next bounds: [0; len(arg)]"
)
if check_count == 0:
return False

Expand Down
2 changes: 1 addition & 1 deletion pandas/io/excel/_odswriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ def _process_style(self, style: dict[str, Any] | None) -> str | None:
style_key = json.dumps(style)
if style_key in self._style_dict:
return self._style_dict[style_key]
name = f"pd{len(self._style_dict)+1}"
name = f"pd{len(self._style_dict) + 1}"
self._style_dict[style_key] = name
odf_style = Style(name=name, family="table-cell")
if "font" in style:
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,8 +336,8 @@ def format_object_summary(

if indent_for_name:
name_len = len(name)
space1 = f'\n{(" " * (name_len + 1))}'
space2 = f'\n{(" " * (name_len + 2))}'
space1 = f"\n{(' ' * (name_len + 1))}"
space2 = f"\n{(' ' * (name_len + 2))}"
else:
space1 = "\n"
space2 = "\n " # space for the opening '['
Expand Down
12 changes: 7 additions & 5 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -2588,7 +2588,7 @@ def set_sticky(
for i, level in enumerate(levels_):
styles.append(
{
"selector": f"thead tr:nth-child({level+1}) th",
"selector": f"thead tr:nth-child({level + 1}) th",
"props": props
+ (
f"top:{i * pixel_size}px; height:{pixel_size}px; "
Expand All @@ -2599,7 +2599,7 @@ def set_sticky(
if not all(name is None for name in self.index.names):
styles.append(
{
"selector": f"thead tr:nth-child({obj.nlevels+1}) th",
"selector": f"thead tr:nth-child({obj.nlevels + 1}) th",
"props": props
+ (
f"top:{(len(levels_)) * pixel_size}px; "
Expand All @@ -2619,7 +2619,7 @@ def set_sticky(
styles.extend(
[
{
"selector": f"thead tr th:nth-child({level+1})",
"selector": f"thead tr th:nth-child({level + 1})",
"props": props_ + "z-index:3 !important;",
},
{
Expand Down Expand Up @@ -4214,8 +4214,10 @@ def css_bar(start: float, end: float, color: str) -> str:
if end > start:
cell_css += "background: linear-gradient(90deg,"
if start > 0:
cell_css += f" transparent {start*100:.1f}%, {color} {start*100:.1f}%,"
cell_css += f" {color} {end*100:.1f}%, transparent {end*100:.1f}%)"
cell_css += (
f" transparent {start * 100:.1f}%, {color} {start * 100:.1f}%,"
)
cell_css += f" {color} {end * 100:.1f}%, transparent {end * 100:.1f}%)"
return cell_css

def css_calc(x, left: float, right: float, align: str, color: str | list | tuple):
Expand Down
11 changes: 4 additions & 7 deletions pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,10 +850,7 @@ def _generate_body_row(

data_element = _element(
"td",
(
f"{self.css['data']} {self.css['row']}{r} "
f"{self.css['col']}{c}{cls}"
),
(f"{self.css['data']} {self.css['row']}{r} {self.css['col']}{c}{cls}"),
value,
data_element_visible,
attributes="",
Expand Down Expand Up @@ -973,7 +970,7 @@ def concatenated_visible_rows(obj):
idx_len = d["index_lengths"].get((lvl, r), None)
if idx_len is not None: # i.e. not a sparsified entry
d["clines"][rn + idx_len].append(
f"\\cline{{{lvln+1}-{len(visible_index_levels)+data_len}}}"
f"\\cline{{{lvln + 1}-{len(visible_index_levels) + data_len}}}"
)

def format(
Expand Down Expand Up @@ -1557,7 +1554,7 @@ def relabel_index(
>>> df = pd.DataFrame({"samples": np.random.rand(10)})
>>> styler = df.loc[np.random.randint(0, 10, 3)].style
>>> styler.relabel_index([f"sample{i+1} ({{}})" for i in range(3)])
>>> styler.relabel_index([f"sample{i + 1} ({{}})" for i in range(3)])
... # doctest: +SKIP
samples
sample1 (5) 0.315811
Expand Down Expand Up @@ -2520,7 +2517,7 @@ def color(value, user_arg, command, comm_arg):
if value[0] == "#" and len(value) == 7: # color is hex code
return command, f"[HTML]{{{value[1:].upper()}}}{arg}"
if value[0] == "#" and len(value) == 4: # color is short hex code
val = f"{value[1].upper()*2}{value[2].upper()*2}{value[3].upper()*2}"
val = f"{value[1].upper() * 2}{value[2].upper() * 2}{value[3].upper() * 2}"
return command, f"[HTML]{{{val}}}{arg}"
elif value[:3] == "rgb": # color is rgb or rgba
r = re.findall("(?<=\\()[0-9\\s%]+(?=,)", value)[0].strip()
Expand Down
6 changes: 3 additions & 3 deletions pandas/io/formats/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def _other_namespaces(self) -> dict:
nmsp_dict: dict[str, str] = {}
if self.namespaces:
nmsp_dict = {
f"xmlns{p if p=='' else f':{p}'}": n
f"xmlns{p if p == '' else f':{p}'}": n
for p, n in self.namespaces.items()
if n != self.prefix_uri[1:-1]
}
Expand Down Expand Up @@ -404,7 +404,7 @@ def _get_prefix_uri(self) -> str:
f"{self.prefix} is not included in namespaces"
) from err
elif "" in self.namespaces:
uri = f'{{{self.namespaces[""]}}}'
uri = f"{{{self.namespaces['']}}}"
else:
uri = ""

Expand Down Expand Up @@ -502,7 +502,7 @@ def _get_prefix_uri(self) -> str:
f"{self.prefix} is not included in namespaces"
) from err
elif "" in self.namespaces:
uri = f'{{{self.namespaces[""]}}}'
uri = f"{{{self.namespaces['']}}}"
else:
uri = ""

Expand Down
Loading

0 comments on commit 581a561

Please sign in to comment.