Skip to content

Commit 9db7f3e

Browse files
guipleiteWillAyd
authored andcommitted
BUG: DataFrame.to_html validates formatters has the correct length (#28632)
1 parent 0ffdbe3 commit 9db7f3e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ I/O
309309
- Bug in :func:`DataFrame.to_string` where values were truncated using display options instead of outputting the full content (:issue:`9784`)
310310
- Bug in :meth:`DataFrame.to_json` where a datetime column label would not be written out in ISO format with ``orient="table"`` (:issue:`28130`)
311311
- Bug in :func:`DataFrame.to_parquet` where writing to GCS would fail with `engine='fastparquet'` if the file did not already exist (:issue:`28326`)
312+
- Bug in :meth:`DataFrame.to_html` where the length of the ``formatters`` argument was not verified (:issue:`28469`)
312313

313314
Plotting
314315
^^^^^^^^

pandas/io/formats/format.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,17 @@ def __init__(
561561
self.sparsify = sparsify
562562

563563
self.float_format = float_format
564-
self.formatters = formatters if formatters is not None else {}
564+
if formatters is None:
565+
self.formatters = {}
566+
elif len(frame.columns) == len(formatters) or isinstance(formatters, dict):
567+
self.formatters = formatters
568+
else:
569+
raise ValueError(
570+
(
571+
"Formatters length({flen}) should match"
572+
" DataFrame number of columns({dlen})"
573+
).format(flen=len(formatters), dlen=len(frame.columns))
574+
)
565575
self.na_rep = na_rep
566576
self.decimal = decimal
567577
self.col_space = col_space

pandas/tests/io/formats/test_to_html.py

+9
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,15 @@ def test_to_html_truncate(datapath):
235235
assert result == expected
236236

237237

238+
@pytest.mark.parametrize("size", [1, 5])
239+
def test_html_invalid_formatters_arg_raises(size):
240+
# issue-28469
241+
df = DataFrame(columns=["a", "b", "c"])
242+
msg = "Formatters length({}) should match DataFrame number of columns(3)"
243+
with pytest.raises(ValueError, match=re.escape(msg.format(size))):
244+
df.to_html(formatters=["{}".format] * size)
245+
246+
238247
def test_to_html_truncate_formatter(datapath):
239248
# issue-25955
240249
data = [

0 commit comments

Comments
 (0)