Skip to content

BUG: Parameter col_space of to_html method not working with multi-level columns #54015

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
merged 17 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
14 changes: 10 additions & 4 deletions pandas/io/formats/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,16 @@ def __init__(
self.table_id = table_id
self.render_links = render_links

self.col_space = {
column: f"{value}px" if isinstance(value, int) else value
for column, value in self.fmt.col_space.items()
}
self.col_space = {}
for column, value in self.fmt.col_space.items():
col_space_value = f"{value}px" if isinstance(value, int) else value
# GH 53885: Handling case where column is MultiIndex
# Flatten the data in the multi index and add in the map
if isinstance(column, tuple):
for column_index in column:
self.col_space[str(column_index)] = col_space_value
else:
self.col_space[column] = col_space_value

def to_string(self) -> str:
lines = self.render()
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/io/formats/data/html/gh53885_expected_output.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<table border="1" class="dataframe">
<thead>
<tr>
<th style="min-width: 100px;"></th>
<th style="min-width: 100px;">1</th>
<th style="min-width: 100px;">2</th>
</tr>
<tr>
<th style="min-width: 100px;"></th>
<th style="min-width: 100px;">1</th>
<th style="min-width: 100px;">1</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>2</td>
</tr>
<tr>
<th>1</th>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
9 changes: 9 additions & 0 deletions pandas/tests/io/formats/test_to_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -896,3 +896,12 @@ def test_to_html_float_format_object_col(datapath):
result = df.to_html(float_format=lambda x: f"{x:,.0f}")
expected = expected_html(datapath, "gh40024_expected_output")
assert result == expected


def test_to_html_multiindex_col_with_colspace(datapath):
# GH#53885
df = DataFrame([[1, 2], [3, 4]])
df.columns = MultiIndex.from_tuples([(1, 1), (2, 1)])
result = df.to_html(col_space=100)
expected = expected_html(datapath, "gh53885_expected_output")
assert result == expected