Skip to content

Commit 9feb3ad

Browse files
ArtificialQualiaWillAyd
authored andcommitted
BUG: Improve col_space in to_html to allow css length strings (#25941) (#26012)
1 parent 51980fe commit 9feb3ad

File tree

5 files changed

+54
-7
lines changed

5 files changed

+54
-7
lines changed

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@ I/O
365365
- Bug in ``read_csv`` which would not raise ``ValueError`` if a column index in ``usecols`` was out of bounds (:issue:`25623`)
366366
- Improved the explanation for the failure when value labels are repeated in Stata dta files and suggested work-arounds (:issue:`25772`)
367367
- Improved :meth:`pandas.read_stata` and :class:`pandas.io.stata.StataReader` to read incorrectly formatted 118 format files saved by Stata (:issue:`25960`)
368+
- Improved the ``col_space`` parameter in :meth:`DataFrame.to_html` to accept a string so CSS length values can be set correctly (:issue:`25941`)
368369
- Fixed bug in loading objects from S3 that contain ``#`` characters in the URL (:issue:`25945`)
369370
- Adds ``use_bqstorage_api`` parameter to :func:`read_gbq` to speed up downloads of large data frames. This feature requires version 0.10.0 of the ``pandas-gbq`` library as well as the ``google-cloud-bigquery-storage`` and ``fastavro`` libraries. (:issue:`26104`)
370371

pandas/core/frame.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,9 @@ def _repr_html_(self):
658658

659659
@Substitution(header='Write out the column names. If a list of strings '
660660
'is given, it is assumed to be aliases for the '
661-
'column names')
661+
'column names',
662+
col_space_type='int',
663+
col_space='The minimum width of each column')
662664
@Substitution(shared_params=fmt.common_docstring,
663665
returns=fmt.return_docstring)
664666
def to_string(self, buf=None, columns=None, col_space=None, header=True,
@@ -2138,7 +2140,12 @@ def to_parquet(self, fname, engine='auto', compression='snappy',
21382140
compression=compression, index=index,
21392141
partition_cols=partition_cols, **kwargs)
21402142

2141-
@Substitution(header='Whether to print column labels, default True')
2143+
@Substitution(header='Whether to print column labels, default True',
2144+
col_space_type='str or int',
2145+
col_space='The minimum width of each column in CSS length '
2146+
'units. An int is assumed to be px units.\n\n'
2147+
' .. versionadded:: 0.25.0\n'
2148+
' Abillity to use str')
21422149
@Substitution(shared_params=fmt.common_docstring,
21432150
returns=fmt.return_docstring)
21442151
def to_html(self, buf=None, columns=None, col_space=None, header=True,

pandas/io/formats/format.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@
4141
Buffer to write to.
4242
columns : sequence, optional, default None
4343
The subset of columns to write. Writes all columns by default.
44-
col_space : int, optional
45-
The minimum width of each column.
44+
col_space : %(col_space_type)s, optional
45+
%(col_space)s.
4646
header : bool, optional
4747
%(header)s.
4848
index : bool, optional, default True

pandas/io/formats/html.py

+28-3
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ def __init__(self, formatter, classes=None, border=None):
4545
self.border = border
4646
self.table_id = self.fmt.table_id
4747
self.render_links = self.fmt.render_links
48+
if isinstance(self.fmt.col_space, int):
49+
self.fmt.col_space = ('{colspace}px'
50+
.format(colspace=self.fmt.col_space))
4851

4952
@property
5053
def show_row_idx_names(self):
@@ -84,8 +87,30 @@ def write(self, s, indent=0):
8487
rs = pprint_thing(s)
8588
self.elements.append(' ' * indent + rs)
8689

87-
def write_th(self, s, indent=0, tags=None):
88-
if self.fmt.col_space is not None and self.fmt.col_space > 0:
90+
def write_th(self, s, header=False, indent=0, tags=None):
91+
"""
92+
Method for writting a formatted <th> cell.
93+
94+
If col_space is set on the formatter then that is used for
95+
the value of min-width.
96+
97+
Parameters
98+
----------
99+
s : object
100+
The data to be written inside the cell.
101+
header : boolean, default False
102+
Set to True if the <th> is for use inside <thead>. This will
103+
cause min-width to be set if there is one.
104+
indent : int, default 0
105+
The indentation level of the cell.
106+
tags : string, default None
107+
Tags to include in the cell.
108+
109+
Returns
110+
-------
111+
A written <th> cell.
112+
"""
113+
if header and self.fmt.col_space is not None:
89114
tags = (tags or "")
90115
tags += ('style="min-width: {colspace};"'
91116
.format(colspace=self.fmt.col_space))
@@ -136,7 +161,7 @@ def write_tr(self, line, indent=0, indent_delta=0, header=False,
136161
for i, s in enumerate(line):
137162
val_tag = tags.get(i, None)
138163
if header or (self.bold_rows and i < nindex_levels):
139-
self.write_th(s, indent, tags=val_tag)
164+
self.write_th(s, indent=indent, header=header, tags=val_tag)
140165
else:
141166
self.write_td(s, indent, tags=val_tag)
142167

pandas/tests/io/formats/test_to_html.py

+14
Original file line numberDiff line numberDiff line change
@@ -641,3 +641,17 @@ def test_to_html_round_column_headers():
641641
notebook = df.to_html(notebook=True)
642642
assert "0.55555" in html
643643
assert "0.556" in notebook
644+
645+
646+
@pytest.mark.parametrize("unit", ['100px', '10%', '5em', 150])
647+
def test_to_html_with_col_space_units(unit):
648+
# GH 25941
649+
df = DataFrame(np.random.random(size=(1, 3)))
650+
result = df.to_html(col_space=unit)
651+
result = result.split('tbody')[0]
652+
hdrs = [x for x in result.split("\n") if re.search(r"<th[>\s]", x)]
653+
if isinstance(unit, int):
654+
unit = str(unit) + 'px'
655+
for h in hdrs:
656+
expected = '<th style="min-width: {unit};">'.format(unit=unit)
657+
assert expected in h

0 commit comments

Comments
 (0)