Skip to content

ENH: update DataFrame to_latex for nicer typesetting #3264

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
Apr 12, 2013
Merged
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
17 changes: 12 additions & 5 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,12 @@ def to_latex(self, force_unicode=None, column_format=None):
"""
Render a DataFrame to a LaTeX tabular environment output.
"""
def get_col_type(dtype):
if issubclass(dtype.type, np.number):
return 'r'
else:
return 'l'

import warnings
if force_unicode is not None: # pragma: no cover
warnings.warn(
Expand All @@ -362,27 +368,28 @@ def to_latex(self, force_unicode=None, column_format=None):
strcols = [[info_line]]
else:
strcols = self._to_str_columns()

if column_format is None:
column_format = '|l|%s|' % '|'.join('c' for _ in strcols)
dtypes = self.frame.dtypes.values
column_format = 'l%s' % ''.join(map(get_col_type, dtypes))
elif not isinstance(column_format, basestring):
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('\\hline\n')
self.buf.write('\\toprule\n')

nlevels = frame.index.nlevels
for i, row in enumerate(izip(*strcols)):
if i == nlevels:
self.buf.write('\\hline\n') # End of header
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('\\hline\n')
self.buf.write('\\bottomrule\n')
self.buf.write('\\end{tabular}\n')

def _format_col(self, i):
Expand Down