pandas.io.formats.style.Styler.to_latex¶
-
Styler.
to_latex
(buf=None, column_format=None, position=None, position_float=None, hrules=False, label=None, caption=None, sparsify=None, multirow_align='c', multicol_align='r', siunitx=False, encoding=None)[source]¶ Write Styler to a file, buffer or string in LaTeX format.
New in version TODO.
- Parameters
- bufstr, Path, or StringIO-like, optional, default None
Buffer to write to. If
None
, the output is returned as a string.- column_formatstr, optional
The LaTeX column specification placed in location:
\begin{tabular}{<column_format>}
Defaults to ‘l’ for index and non-numeric data columns, otherwise ‘r’ (or ‘S’ if using the {siunitx} package).
- positionstr, optional
The LaTeX positional argument (e.g. ‘h!’) for tables, placed in location:
\begin{table}[<position>]
- position_float{“centering”, “raggedleft”, “raggedright”}, optional
The LaTeX float command placed in location:
\begin{table}[<position>]
\<position_float>
- hrulesbool, default False
Set to True to add \toprule, \midrule and \bottomrule from the {booktabs} LaTeX package.
- labelstr, optional
The LaTeX label included as: \label{<label>}. This is used with \ref{<label>} in the main .tex file.
- captionstr, optional
The LaTeX table caption included as: \caption{<caption>}.
- sparsifybool, optional
Set to
False
to print every item of a hierarchical MultiIndex. Defaults to the pandasmulti_sparse
display option.- multirow_align{“c”, “t”, “b”}
If sparsifying hierarchical MultiIndexes whether to align text centrally, at the top or bottom.
- multicol_align{“r”, “c”, “l”}
If sparsifying hierarchical MultiIndex columns whether to align text at the left, centrally, or at the right.
- siunitxbool, default False
Set to
True
to structure LaTeX compatible with the {siunitx} package.- encodingstr, default “utf-8”
Character encoding setting.
- Returns
- str or None
If buf is None, returns the result as a string. Otherwise returns None.
See also
Styler.format
Format the text display value of cells.
Notes
Latex Packages
For the following features we recommend the following LaTeX inclusions:
Feature
Inclusion
sparse columns
none: included within default {tabular} environment
sparse rows
\usepackage{multirow}
hrules
\usepackage{booktabs}
colors
\usepackage[table]{xcolor}
siunitx §
\usepackage{siunitx}
bold (with siunitx)
\usepackage{etoolbox}\robustify\bfseries\sisetup{detect-all = true} (within {document})italic (with siunitx)
\usepackage{etoolbox}\robustify\itshape\sisetup{detect-all = true} (within {document})§: if using the
siunitx
argument then numeric columns will be set to acolumn_format
of “S” instead of “r”.Cell Styles
LaTeX styling can only be rendered if the accompanying styling functions have been constructed with appropriate LaTeX commands. All styling functionality is built around the concept of a CSS
(<attribute>, <value>)
pair (see Table Visualization), and this should be replaced by a LaTeX(<command>, <options>)
approach and each cell will be styled individually using nested LaTeX commands with their accompanied options.For example the following code will highlight and bold a cell in HTML-CSS:
>>> df = pd.DataFrame([[1,2], [3,4]]) >>> s = df.style.highlight_max(axis=None, ... props='background-color:red; font-weight:bold;') >>> s.render()
The equivalent using LaTeX only commands is the following:
>>> s = df.style.highlight_max(axis=None, ... props='color:{red}; bfseries: ;') >>> s.to_latex()
Internally these structured LaTeX
(<command>, <options>)
pairs are translated to thedisplay_value
with the default structure:\<command><options> <display_value>
. Where there are multiple commands the latter is nested recursively, so that the above example highlighed cell is rendered as\color{red} \bfseries 4
.Occasionally this format does not suit the applied command, or combination of LaTeX packages that is in use, so additional flags can be added to the
<options>
, within the tuple, to result in different positions of required braces (the default being the same as--nowrap
):Tuple Format
Output Structure
(<command>,<options>)
\<command><options> <display_value>
(<command>,<options>
--nowrap
)\<command><options> <display_value>
(<command>,<options>
--rwrap
)\<command><options>{<display_value>}
(<command>,<options>
--wrap
){\<command><options> <display_value>}
(<command>,<options>
--lwrap
){\<command><options>} <display_value>
(<command>,<options>
--dwrap
){\<command><options>}{<display_value>}
For example the textbf command for font-weight should always be used with –rwrap so
('textbf', '--rwrap')
will render a working cell, wrapped with braces, as\textbf{<display_value>}
.A more comprehensive example is as follows:
>>> df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]], ... index=["ix1", "ix2", "ix3"], ... columns=["Integers", "Floats", "Strings"]) >>> s = df.style.highlight_max( ... props='cellcolor:[HTML]{FFFF00}; color:{red};' ... 'textit:--rwrap; textbf:--rwrap;' ... ) >>> s.to_latex()
Table Styles
Internally Styler uses its
table_styles
object to parse the following input arguments:column_format
position
position_float
hrules (including the toprule, midrule and bottomrule sub commands)
label
These command arguments (except for
caption
) are added in the following way:>>> s.set_table_styles([{'selector': '<command>', 'props': ':<options>;'}], ... overwrite=False)
For example, if setting a
column_format
, this is internally recorded as:>>> s.set_table_styles([{'selector': 'column_format', 'props': ':rcll;'}], ... overwrite=False])
Note that since
labels
often include ‘:’ but this is used as a CSS separator, there is a character replacement, substituting ‘:’ for ‘§’, so a label of ‘fig:item1’ is recorded as:>>> s.set_table_styles([{'selector': 'label', 'props': ':{fig§item1};'}], ... overwrite=False])
Any custom commands you add to
table_styles
are included and positioned immediately above the ‘\begin{tabular}’ command. For example to add odd and even row coloring, from the {colortbl} package, use:>>> s.set_table_styles([{'selector': 'rowcolors', 'props': ':{1}{pink}{red};'}], ... overwrite=False])
A more comprehensive example using these arguments is as follows:
>>> df.columns = pd.MultiIndex.from_tuples([ ... ("Numeric", "Integers"), ... ("Numeric", "Floats"), ... ("Non-Numeric", "Strings") ... ]) >>> df.index = pd.MultiIndex.from_tuples([ ... ("L0", "ix1"), ("L0", "ix2"), ("L1", "ix3") ... ]) >>> s = df.style.highlight_max( ... props='cellcolor:[HTML]{FFFF00}; color:{red}; itshape:; bfseries:;' ... ) >>> s.to_latex( ... column_format="rrrrr", position="h", position_float="centering", ... hrules=True, label="table:5", caption="Styled LaTeX Table", ... multirow_align="t", multicol_align="r" ... )
Formatting
To format values
Styler.format()
should be used prior to calling Styler.to_latex, for example:>>> s.clear() >>> s.table_styles = [] >>> s.caption = None >>> s.format({ ... ("Numeric", "Integers"): '\${}', ... ("Numeric", "Floats"): '{:.3f}', ... ("Non-Numeric", "Strings"): str.upper ... }) >>> s.to_latex() \\begin{tabular}{llrrl} {} & {} & \\multicolumn{2}{r}{Numeric} & {Non-Numeric} \\\\ {} & {} & {Integers} & {Floats} & {Strings} \\\\ \\multirow[c]{2}{*}{L0} & ix1 & \\$1 & 2.200 & DOGS \\ & ix2 & \\$3 & 4.400 & CATS \\\\ L1 & ix3 & \\$2 & 6.600 & COWS \\\\ \\end{tabular}