Skip to content

ENH: allow to_html and to_latex to take a path for their first argument #3702

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 1 commit into from
May 30, 2013
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions RELEASE.rst
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ pandas 0.11.1
into today's date
- ``DataFrame.from_records`` did not accept empty recarrays (GH3682_)
- ``DataFrame.to_csv`` will succeed with the deprecated option ``nanRep``, @tdsmith
- ``DataFrame.to_html`` and ``DataFrame.to_latex`` now accept a path for
their first argument (GH3702_)

.. _GH3164: https://github.com/pydata/pandas/issues/3164
.. _GH2786: https://github.com/pydata/pandas/issues/2786
Expand Down Expand Up @@ -255,6 +257,7 @@ pandas 0.11.1
.. _GH3676: https://github.com/pydata/pandas/issues/3676
.. _GH3675: https://github.com/pydata/pandas/issues/3675
.. _GH3682: https://github.com/pydata/pandas/issues/3682
.. _GH3702: https://github.com/pydata/pandas/issues/3702

pandas 0.11.0
=============
Expand Down
4 changes: 4 additions & 0 deletions doc/source/v0.11.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ Bug Fixes

- ``DataFrame.from_records`` did not accept empty recarrays (GH3682_)

- ``DataFrame.to_html`` and ``DataFrame.to_latex`` now accept a path for
their first argument (GH3702_)

See the `full release notes
<https://github.com/pydata/pandas/blob/master/RELEASE.rst>`__ or issue tracker
on GitHub for a complete list.
Expand Down Expand Up @@ -274,3 +277,4 @@ on GitHub for a complete list.
.. _GH3675: https://github.com/pydata/pandas/issues/3675
.. _GH3682: https://github.com/pydata/pandas/issues/3682
.. _GH3679: https://github.com/pydata/pandas/issues/3679
.. _GH3702: https://github.com/pydata/pandas/issues/3702
50 changes: 33 additions & 17 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,21 +364,31 @@ def get_col_type(dtype):
raise AssertionError(('column_format must be str or unicode, not %s'
% type(column_format)))

self.buf.write('\\begin{tabular}{%s}\n' % column_format)
self.buf.write('\\toprule\n')

nlevels = frame.index.nlevels
for i, row in enumerate(izip(*strcols)):
if i == nlevels:
self.buf.write('\\midrule\n') # End of header
crow = [(x.replace('_', '\\_')
.replace('%', '\\%')
.replace('&', '\\&') if x else '{}') for x in row]
self.buf.write(' & '.join(crow))
self.buf.write(' \\\\\n')

self.buf.write('\\bottomrule\n')
self.buf.write('\\end{tabular}\n')
def write(buf, frame, column_format, strcols):
buf.write('\\begin{tabular}{%s}\n' % column_format)
buf.write('\\toprule\n')

nlevels = frame.index.nlevels
for i, row in enumerate(izip(*strcols)):
if i == nlevels:
buf.write('\\midrule\n') # End of header
crow = [(x.replace('_', '\\_')
.replace('%', '\\%')
.replace('&', '\\&') if x else '{}') for x in row]
buf.write(' & '.join(crow))
buf.write(' \\\\\n')

buf.write('\\bottomrule\n')
buf.write('\\end{tabular}\n')

if hasattr(self.buf, 'write'):
write(self.buf, frame, column_format, strcols)
elif isinstance(self.buf, basestring):
with open(self.buf, 'w') as f:
write(f, frame, column_format, strcols)
else:
raise TypeError('buf is not a file name and it has no write '
'method')

def _format_col(self, i):
formatter = self._get_formatter(i)
Expand All @@ -392,7 +402,14 @@ def to_html(self, classes=None):
Render a DataFrame to a html table.
"""
html_renderer = HTMLFormatter(self, classes=classes)
html_renderer.write_result(self.buf)
if hasattr(self.buf, 'write'):
html_renderer.write_result(self.buf)
elif isinstance(self.buf, basestring):
with open(self.buf, 'w') as f:
html_renderer.write_result(f)
else:
raise TypeError('buf is not a file name and it has no write '
' method')

def _get_formatted_column_labels(self):
from pandas.core.index import _sparsify
Expand Down Expand Up @@ -574,7 +591,6 @@ def write_result(self, buf):
indent = self._write_body(indent)

self.write('</table>', indent)

_put_lines(buf, self.elements)

def _write_header(self, indent):
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1222,7 +1222,11 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None,
if buf is None:
return the_repr
else:
print >> buf, the_repr
try:
buf.write(the_repr)
except AttributeError:
with open(buf, 'w') as f:
f.write(the_repr)

def _get_repr(self, name=False, print_header=False, length=True, dtype=True,
na_rep='NaN', float_format=None):
Expand Down
27 changes: 27 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,26 @@ def test_to_html(self):
frame = DataFrame(index=np.arange(200))
frame.to_html()

def test_to_html_filename(self):
biggie = DataFrame({'A': randn(200),
'B': tm.makeStringIndex(200)},
index=range(200))

biggie['A'][:20] = nan
biggie['B'][:20] = nan
with tm.ensure_clean('test.html') as path:
biggie.to_html(path)
with open(path, 'r') as f:
s = biggie.to_html()
s2 = f.read()
self.assertEqual(s, s2)

frame = DataFrame(index=np.arange(200))
with tm.ensure_clean('test.html') as path:
frame.to_html(path)
with open(path, 'r') as f:
self.assertEqual(frame.to_html(), f.read())

def test_to_html_with_no_bold(self):
x = DataFrame({'x': randn(5)})
ashtml = x.to_html(bold_rows=False)
Expand Down Expand Up @@ -1474,6 +1494,13 @@ def test_dict_entries(self):
self.assertTrue("'a': 1" in val)
self.assertTrue("'b': 2" in val)

def test_to_latex_filename(self):
with tm.ensure_clean('test.tex') as path:
self.frame.to_latex(path)

with open(path, 'r') as f:
self.assertEqual(self.frame.to_latex(), f.read())

def test_to_latex(self):
# it works!
self.frame.to_latex()
Expand Down