Skip to content

Commit 0c67f13

Browse files
gabriellm1TomAugspurger
authored andcommitted
BUG: to_html() with formatters=<list> and max_cols fixed (#28183)
* BUG: issue-25955 fixed
1 parent 4e43629 commit 0c67f13

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

doc/source/whatsnew/v1.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Performance improvements
107107
Bug fixes
108108
~~~~~~~~~
109109

110+
- Bug in :meth:`DataFrame.to_html` when using ``formatters=<list>`` and ``max_cols`` together. (:issue:`25955`)
110111

111112
Categorical
112113
^^^^^^^^^^^

pandas/io/formats/format.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,13 @@ def _chk_truncate(self) -> None:
657657
frame = concat(
658658
(frame.iloc[:, :col_num], frame.iloc[:, -col_num:]), axis=1
659659
)
660+
# truncate formatter
661+
if isinstance(self.formatters, (list, tuple)):
662+
truncate_fmt = self.formatters
663+
self.formatters = [
664+
*truncate_fmt[:col_num],
665+
*truncate_fmt[-col_num:],
666+
]
660667
self.tr_col_num = col_num
661668
if truncate_v:
662669
# cast here since if truncate_v is True, max_rows_adj is not None
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<table border="1" class="dataframe">
2+
<thead>
3+
<tr style="text-align: right;">
4+
<th></th>
5+
<th>A</th>
6+
<th>...</th>
7+
<th>D</th>
8+
</tr>
9+
</thead>
10+
<tbody>
11+
<tr>
12+
<th>0</th>
13+
<td>1_mod</td>
14+
<td>...</td>
15+
<td>4</td>
16+
</tr>
17+
<tr>
18+
<th>1</th>
19+
<td>5_mod</td>
20+
<td>...</td>
21+
<td>8</td>
22+
</tr>
23+
<tr>
24+
<th>2</th>
25+
<td>9_mod</td>
26+
<td>...</td>
27+
<td>12</td>
28+
</tr>
29+
<tr>
30+
<th>3</th>
31+
<td>13_mod</td>
32+
<td>...</td>
33+
<td>16</td>
34+
</tr>
35+
</tbody>
36+
</table>

pandas/tests/io/formats/test_to_html.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,23 @@ def test_to_html_truncate(datapath):
235235
assert result == expected
236236

237237

238+
def test_to_html_truncate_formatter(datapath):
239+
# issue-25955
240+
data = [
241+
{"A": 1, "B": 2, "C": 3, "D": 4},
242+
{"A": 5, "B": 6, "C": 7, "D": 8},
243+
{"A": 9, "B": 10, "C": 11, "D": 12},
244+
{"A": 13, "B": 14, "C": 15, "D": 16},
245+
]
246+
247+
df = DataFrame(data)
248+
fmt = lambda x: str(x) + "_mod"
249+
formatters = [fmt, fmt, None, None]
250+
result = df.to_html(formatters=formatters, max_cols=3)
251+
expected = expected_html(datapath, "truncate_formatter")
252+
assert result == expected
253+
254+
238255
@pytest.mark.parametrize(
239256
"sparsify,expected",
240257
[(True, "truncate_multi_index"), (False, "truncate_multi_index_sparse_off")],

0 commit comments

Comments
 (0)