Table Styling
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
DataFrame.style returns a Styler, an object that wraps a DataFrame and describes how to display it: number formats,
colours, borders, a caption, hidden rows, tooltips. The data itself never changes. A Styler renders to HTML (which is what
a notebook shows), and it can also write LaTeX, Excel, Typst and plain text. It is the pandas tool for tables that people
will read, such as a report, an email or a thesis, as opposed to the tables that other programs will read.
This page targets pandas 3.1 on Python 3.13 or 3.14 and was checked in October 2026; every example was run with Python 3.13, pandas 3.1.0, Jinja2 3.1.6 and Matplotlib 3.11, and the printed output is the real output. Because a browser is not needed to check what a rule did, the examples print the generated CSS, or the plain-text and LaTeX rendering, instead of showing screenshots. For the tool that chooses and formats the data that goes into a Styler, see DataFrame; for charts, see Charts with pandas.
Requirements
The Styler needs Jinja2 (3.1.6 or newer), which is an optional dependency installed by the output-formatting extra, together
with tabulate, which is used by to_markdown. Colour gradients need Matplotlib (the plot extra). Without Jinja2 the
.style attribute does not exist:
pip install "pandas[output-formatting,plot]"
import sys
sys.modules["jinja2"] = None # simulate a missing package
import pandas as pd
try:
pd.DataFrame([[1]]).style
except AttributeError as exc:
print(type(exc).__name__, exc)
AttributeError The '.style' accessor requires jinja2
How a Styler works
A Styler keeps three things: the DataFrame, a list of display functions (formatters) that turn each value into a string,
and a list of style functions that produce CSS for each cell. Nothing is computed until the Styler is rendered, which
is why the methods are cheap and why they can be chained. Every method modifies the Styler and returns it, so
styler.format(...) and styler = styler.format(...) are equivalent.
Source: pandas API reference: Style.
A first styled table
The following table has a missing value, a negative growth rate and a stock count. It is formatted for display, the missing cell and the best revenue are highlighted, the negative growth is shown in red, and a caption is added.
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"revenue": [125000.5, 98000.0, np.nan, 15400.25],
"growth": [0.153, -0.042, 0.071, 0.2],
"stock": [12, 0, 45, 8],
},
index=pd.Index(["Laptop", "Phone", "Tablet", "Watch"], name="product"),
)
styler = (
df.style
.set_uuid("sales")
.format({"revenue": "${:,.0f}", "growth": "{:+.1%}", "stock": "{:d}"}, na_rep="n/a")
.highlight_null(color="#fde68a")
.highlight_max(subset=["revenue"], color="#bbf7d0")
.map(lambda v: "color: #b91c1c; font-weight: bold" if v < 0 else "", subset=["growth"])
.set_caption("Quarterly figures")
)
print(type(styler).__name__, styler.data is df)
html = styler.to_html()
print(html[:330])
print(styler.to_string())
Styler True
<style type="text/css">
#T_sales_row0_col0 {
background-color: #bbf7d0;
}
#T_sales_row1_col1 {
color: #b91c1c;
font-weight: bold;
}
#T_sales_row2_col0 {
background-color: #fde68a;
}
</style>
<table id="T_sales">
<caption>Quarterly figures</caption>
<thead>
<tr>
<th class="blank level0" > </th>
<t
revenue growth stock
product
Laptop $125,000 +15.3% 12
Phone $98,000 -4.2% 0
Tablet n/a +7.1% 45
Watch $15,400 +20.0% 8
The HTML consists of a <style> block that targets cells by generated ids (T_sales_row0_col0 is the cell in row 0 and
column 0) and a table. The id prefix is random unless you call set_uuid; fix it when the HTML is compared in tests or
embedded in a page that has several tables. A notebook displays a Styler by rendering this HTML, and
styler.to_html() returns it as a string, or writes it to a file when you pass a path.
Formatting values
Styler.format changes only how a value is shown. It accepts one formatter for the whole table, or a dictionary from column
names to formatters, and subset restricts the cells. A formatter is a format string such as "{:.2f}", or a function that returns
a string. The keyword arguments precision, thousands, decimal and na_rep cover common cases without a format
string, and escape and hyperlinks convert the text for HTML or LaTeX.
t = pd.DataFrame(
{
"name": ["<b>Ada</b>", "R&D", "Bob"],
"amount": [1234567.891, 2.5, np.nan],
"url": ["https://example.com", "", "https://pandas.pydata.org"],
}
)
print(t.style.format({"amount": "{:,.2f}"}, na_rep="-").to_string())
print(t.style.format(precision=1, thousands=" ", decimal=",").to_string())
print(t.style.format({"url": lambda u: u}, hyperlinks="html").to_html(exclude_styles=True).count("<a href"))
name amount url 0 <b>Ada</b> 1,234,567.89 https://example.com 1 R&D 2.50 2 Bob - https://pandas.pydata.org name amount url 0 <b>Ada</b> 1 234 567,9 https://example.com 1 R&D 2,5 2 Bob nan https://pandas.pydata.org 2
Four details deserve attention:
-
Without
na_rep, a missing value is shown asnan; set it once withformat(na_rep="-")or with the optionstyler.format.na_rep. -
escape="html"turns<,>and&into entities so that data cannot inject markup into the page, andescape="latex"escapes the special characters of LaTeX. Always escape text that comes from users or from files you do not control. -
The escaping is applied before a callable formatter runs. Combining
escape="html"with a function that changes the text, such asstr.upper, therefore produces broken entities (<B>). Escape in the function itself when you need both. -
The formatter changes only the displayed string. The values in
styler.data, and in the Excel cells written byto_excel, keep their original numbers (see the Excel section below).
Row and column labels have their own methods: format_index formats the labels, relabel_index replaces them, and
format_index_names formats the names of the index and the columns (new in pandas 3.0).
print(t.style.format_index(str.upper, axis=1).to_string())
print(t.style.relabel_index(["first", "second", "third"], axis=0).to_string())
print(t.style.hide(axis="index").hide(subset=["url"], axis="columns").to_string())
print(df.style.format_index_names(str.upper, axis=0).to_string())
NAME AMOUNT URL 0 <b>Ada</b> 1234567.891000 https://example.com 1 R&D 2.500000 2 Bob nan https://pandas.pydata.org name amount url first <b>Ada</b> 1234567.891000 https://example.com second R&D 2.500000 third Bob nan https://pandas.pydata.org name amount <b>Ada</b> 1234567.891000 R&D 2.500000 Bob nan revenue growth stock PRODUCT Laptop 125000.500000 0.153000 12 Phone 98000.000000 -0.042000 0 Tablet nan 0.071000 45 Watch 15400.250000 0.200000 8
The last table has the same values as before, with full precision because no value formatter is set; the index name now reads
PRODUCT.
Source: Styler.format, Styler.format_index and Styler.relabel_index.
Conditional styling with map and apply
Two methods apply a function that returns CSS declarations (a string such as "color: red; font-weight: bold"):
-
Styler.map(func)callsfuncon every value and must return one string per value. It replacesapplymap, which was deprecated in pandas 2.1 and is no longer available in 3.1. -
Styler.apply(func, axis=0)callsfuncon each column (axis=0), each row (axis=1) or the whole frame (axis=None), and must return an object of the same shape, with one CSS string per cell.Styler.map_indexandStyler.apply_indexdo the same for the row and column labels.
Both take subset, a column name, a list of labels or an index-and-column slice built with pd.IndexSlice, and pass extra
keyword arguments to the function.
To see what a rule did without a browser, the helper below parses the generated CSS and lists the cells (row label plus column label) that received each declaration. It is a teaching aid, not part of pandas.
import re
scores = pd.DataFrame(
[[2.04, -2.56, 0.42], [-0.57, -0.45, -0.22], [-2.02, -0.23, -0.87], [3.32, 0.23, -0.35]],
columns=list("ABC"),
index=list("wxyz"),
)
def styled_cells(styler):
"""Map each CSS rule to the cells (row label + column label) that received it."""
data = styler.data
html = styler.set_uuid("t").to_html()
found = {}
for ids, css in re.findall(r"((?:#T_t_row\d+_col\d+(?:, )?)+) \{\n (.*?);?\n\}", html):
cells = [data.index[int(r)] + data.columns[int(c)]
for r, c in re.findall(r"row(\d+)_col(\d+)", ids)]
found[css] = cells
return found
def bold_max(col):
return np.where(col == col.max(), "font-weight: bold", "")
print(styled_cells(scores.style.map(lambda v: "color: red" if v < 0 else "")))
print(styled_cells(scores.style.map(lambda v: "color: red" if v < 0 else "", subset=pd.IndexSlice["w":"x", ["A", "C"]])))
print(styled_cells(scores.style.apply(bold_max, axis=0)))
print(styled_cells(scores.style.apply(lambda row: ["color: red" if v == row.min() else "" for v in row], axis=1)))
{'color: red': ['wB', 'xA', 'xB', 'xC', 'yA', 'yB', 'yC', 'zC']}
{'color: red': ['xA', 'xC']}
{'font-weight: bold': ['wC', 'zA', 'zB']}
{'color: red': ['wB', 'xA', 'yA', 'zC']}
The first result lists every negative cell; the second shows subset limiting the rule to the cells in rows w to x (a label
slice is inclusive on both ends) and columns A and C; the third bolds the largest value of each column and the fourth
marks the smallest value of each row.
An apply function that works on a column must return a sequence of the same length, and a function with axis=None must
return a DataFrame with the same index and columns. A common source of errors is returning a list of the wrong length; the
resulting ValueError points at the function.
Source: Styler.map and Styler.apply.
Built-in highlights, gradients and bars
Several common rules are available as methods, so you do not have to write the function:
| Method | Effect |
|---|---|
|
Colours the largest or smallest value of each column ( |
|
Colours missing values. |
|
Colours values within |
|
Colours values between two quantiles of the data. |
|
Colours each cell by its value along a Matplotlib colormap; text colour adapts to the background. |
|
The same, colouring the text instead of the background. |
|
Draws an in-cell bar proportional to the value; |
print(styled_cells(scores.style.highlight_max(color="gold")))
print(styled_cells(scores.style.highlight_between(left=-0.5, right=0.5, props="color: red")))
print(styled_cells(scores.style.highlight_quantile(q_left=0.75, axis=None, props="font-weight: bold")))
g = scores.style.background_gradient(cmap="Blues", axis=None, vmin=-2, vmax=2).set_uuid("g").to_html()
print("background-color: #" in g)
print("linear-gradient" in scores.style.bar(subset=["A"], color=["#fca5a5", "#86efac"], align="zero").to_html())
{'background-color: gold': ['wC', 'zA', 'zB']}
{'color: red': ['wC', 'xB', 'xC', 'yB', 'zB', 'zC']}
{'font-weight: bold': ['wA', 'wC', 'zA']}
True
True
The last two lines confirm that the gradient wrote colours and that bar produced a linear-gradient background for the in-cell
bars. Use axis=None with a shared vmin and vmax when all columns share a unit, and axis=0 (the default) when each column
has its own scale. A colour scale is a design decision: use a sequential map for magnitudes, a diverging map centred on zero
for values that go both ways, and avoid red-green pairs for readers with colour-vision deficiency.
Table-wide CSS, caption, hiding and sticky headers
set_table_styles adds CSS rules by selector: a tag ("th"), a class, a pseudo-class ("tr:hover td"), or per column
and row label with a dictionary. set_properties sets declarations for the cells in a subset, set_table_attributes adds attributes to the <table> tag
(for example a CSS class from your page), set_caption adds the caption, and hide removes the index, the columns, a level or
the names. set_sticky keeps headers visible while scrolling.
report = pd.DataFrame(
{"revenue": [125000.5, 98000.0, 15400.25], "growth": [0.153, -0.042, 0.2]},
index=pd.Index(["Laptop", "Phone", "Watch"], name="product"),
)
styler = (
report.style
.set_uuid("sales")
.format({"revenue": "{:,.0f}", "growth": "{:+.1%}"})
.set_table_styles([
{"selector": "th", "props": [("background-color", "#0f172a"), ("color", "white")]},
{"selector": "tr:hover td", "props": "background-color: #e2e8f0"},
{"selector": "td", "props": "text-align: right"},
])
.set_properties(subset=["growth"], **{"font-style": "italic"})
.set_table_attributes('class="report"')
.set_caption("Sales by product")
)
html = styler.to_html()
print(html.split("</style>")[0])
print(html.split("</style>")[1][:120])
<style type="text/css">
#T_sales th {
background-color: #0f172a;
color: white;
}
#T_sales tr:hover td {
background-color: #e2e8f0;
}
#T_sales td {
text-align: right;
}
#T_sales_row0_col1, #T_sales_row1_col1, #T_sales_row2_col1 {
font-style: italic;
}
<table id="T_sales" class="report">
<caption>Sales by product</caption>
<thead>
<tr>
<th class="blank lev
Notice that table styles are written against the table id, so they affect only this table, and that the per-cell styles come after
them. By default set_table_styles replaces earlier table styles; pass overwrite=False to add to them. hide has these
forms:
-
hide(axis="index")hides the row labels, andhide(axis="columns")the column headers. -
hide(subset=[...], axis="index")hides rows by label, andhide(subset=[...], axis="columns")hides columns by label. -
hide(level=...)hides one level of a MultiIndex, andhide(names=True)hides the index or column names.
The old methods hide_index and hide_columns do not exist in pandas 3.1; use hide.
Tooltips
set_tooltips attaches a text to cells from a DataFrame of the same shape (an empty string means no tooltip). By default it adds a
CSS-driven element; since pandas 3.0 you can set as_title_attribute=True to use the standard title attribute of the cell
instead, which also works where the page cannot carry custom CSS, such as an email.
tips = pd.DataFrame({"a": ["best", ""]}, index=["x", "y"])
small = pd.DataFrame({"a": [1, 2]}, index=["x", "y"])
print(small.style.set_uuid("s").set_tooltips(tips, as_title_attribute=True).to_html().split("<tbody>")[1].split("</tr>")[0])
<tr>
<th id="T_s_level0_row0" class="row_heading level0 row0" >x</th>
<td id="T_s_row0_col0" class="data row0 col0" title="best">1</td>
set_td_classes is the related tool for CSS classes: give a DataFrame of class names and style them in your own stylesheet.
Using classes keeps the colours out of the Python code, so a designer can change them.
Totals, reuse and pipelines
Styler.concat appends the rendering of another Styler below the table, which is the way to add a totals row without putting it
in the data. Styler.export returns the styles of a Styler as a dictionary, and Styler.use applies them to another Styler;
pipe passes the Styler to your own function so that a house style can be written once. Note that export carries the
styles (apply, map, highlight_*, table styles, hide settings) but not the formatters.
summary = pd.DataFrame(
{"revenue": [125000.5, 98000.0, 15400.25], "growth": [0.153, -0.042, 0.2]},
index=pd.Index(["Laptop", "Phone", "Watch"], name="product"),
)
s = summary.style
print(s.format("{:.1f}") is s) # methods modify and return the same Styler
totals = summary.agg(["sum"]).style.format("{:,.2f}")
print(summary.style.format("{:,.2f}").concat(totals).to_string())
base = summary.style.highlight_max(color="gold").format("{:.1f}")
settings = base.export()
print(sorted(settings))
other = pd.DataFrame({"revenue": [5.0, 6.0], "growth": [7.0, 8.0]}).style.use(settings)
print(other.to_string())
print(other.set_uuid("o").to_html().count("background-color: gold"))
def house_style(styler):
return styler.set_table_attributes('class="report"').set_properties(**{"text-align": "right"})
print(summary.style.pipe(house_style).set_uuid("h").to_html().count("text-align: right"))
True revenue growth product Laptop 125,000.50 0.15 Phone 98,000.00 -0.04 Watch 15,400.25 0.20 sum 238,400.75 0.31 ['apply', 'css', 'hide_column_names', 'hide_columns', 'hide_index', 'hide_index_names', 'table_attributes', 'table_styles'] revenue growth 0 5.000000 7.000000 1 6.000000 8.000000 1 1
pipe hands the Styler to a function, so the house style is applied by one call; export shows the keys of the dictionary
(the keys hide_index and hide_columns are internal names of the exported state, not methods).
Source: Styler.concat and Styler.export.
Exporting
A Styler writes to several formats. All of them take the formatted strings, and each format keeps a different part of the styling.
| Method | Output | What is kept |
|---|---|---|
|
HTML string or file |
Everything. |
|
LaTeX |
Formats, caption, label, |
|
An |
Cell fills, fonts, borders and alignment from the CSS subset that Excel understands; |
|
Typst |
Formatted strings, with escaping; no colours. |
|
Plain text |
Formatted strings only; useful for logs and tests. |
sales = pd.DataFrame(
{"revenue": [125000.5, 98000.0, 15400.25], "growth": [0.153, -0.042, 0.2], "region": ["EU", "US", "A&B"]},
index=pd.Index(["Laptop", "Phone", "Watch"], name="product"),
)
styler = (
sales.style
.format({"revenue": "{:,.0f}", "growth": "{:+.1%}"}, escape="latex")
.set_caption("Sales")
.highlight_max(subset="revenue", props="font-weight: bold;")
.map(lambda v: "color: red;" if v < 0 else "", subset="growth")
)
print(styler.to_latex(hrules=True, convert_css=True, label="tab:sales", position_float="centering"))
print(styler.to_typst())
Source: Styler.to_excel and Styler.to_latex.
\begin{table}
\centering
\caption{Sales}
\label{tab:sales}
\begin{tabular}{lrrl}
\toprule
& revenue & growth & region \\
product & & & \\
\midrule
Laptop & \bfseries 125,000 & +15.3% & EU \\
Phone & 98,000 & \color{red} -4.2% & US \\
Watch & 15,400 & +20.0% & A\&B \\
\bottomrule
\end{tabular}
\end{table}
#table(
columns: 4,
[], [revenue], [growth], [region],
[product], [], [], [],
[Laptop], [125,000], [+15.3%], [EU],
[Phone], [98,000], [-4.2%], [US],
[Watch], [15,400], [+20.0%], [A\&B],
)
The LaTeX output contains \bfseries and \color{red} because convert_css=True translated the CSS; the \color command needs
the xcolor package. The ampersand in A&B is escaped because the formatter used escape="latex", and the Typst output shows
that the escaping chosen with format applies to every renderer, so choose the escape for the target.
to_latex also accepts column_format, siunitx=True for aligned numbers, environment, multirow_align
and multicol_align, sparse_index and sparse_columns for MultiIndex headers. Options such as
styler.latex.hrules set the defaults.
Excel
Styler.to_excel writes the styled table, and it is the only way to get styling in the spreadsheet: since pandas 3.0
DataFrame.to_excel produces an unstyled sheet (no bold header, no borders), unlike earlier versions. The example writes a
styled and a plain workbook and reads them back with openpyxl to show the difference.
import openpyxl
xl = pd.DataFrame({"a": [1.0, -2.5, 3.25], "b": [10, 20, 30]})
s = xl.style.map(lambda v: "background-color: #fecaca; font-weight: bold" if v < 0 else "").format("{:.1f}")
s.to_excel("styled.xlsx", sheet_name="Report", engine="openpyxl", freeze_panes=(1, 1), autofilter=True)
xl.to_excel("plain.xlsx", engine="openpyxl")
ws = openpyxl.load_workbook("styled.xlsx")["Report"]
print(ws["B3"].fill.fgColor.rgb, ws["B3"].font.b, ws["B3"].number_format, ws.freeze_panes, ws.auto_filter.ref)
print(ws["B2"].value, ws["B3"].value)
ws2 = openpyxl.load_workbook("plain.xlsx").active
print(ws2["B1"].font.b, ws2["B1"].fill.fgColor.rgb)
00FECACA True General B2 A1:C4 1 -2.5 False 00000000
The negative cell has the red fill and bold font, and the sheet has frozen panes and an autofilter over A1:C4. The number format
is General: the "{:.1f}" formatter only affects displayed strings, so apply a number format in Excel (or round the
data) if the spreadsheet must show one decimal. The autofilter parameter is new in pandas 3.0, as is the value "columns"
for merge_cells. Excel also limits a cell to 32,767 characters, and pandas 3.0 emits a UserWarning when a cell is longer.
The Excel writers and engines are covered in Excel.
Source: Styler.to_excel and Styler.to_latex.
Options and large tables
A Styler renders every cell, so a very large table makes huge HTML. The options styler.render.max_rows,
styler.render.max_columns and styler.render.max_elements (default 262144 cells) limit how much of the table is rendered; to_html(max_rows=..., max_columns=...) does the same for one call. Other options set defaults:
styler.format.precision, styler.format.thousands, styler.format.decimal, styler.format.na_rep, styler.format.escape,
styler.format.formatter, styler.sparse.index and styler.sparse.columns (merge repeated labels of a MultiIndex),
styler.html.mathjax, styler.latex.environment, styler.latex.hrules, styler.latex.multicol_align,
styler.latex.multirow_align, styler.render.encoding and styler.render.repr ("html" or "latex"). They are listed with
pd.describe_option("styler"); see Options and Settings.
A Styler requires unique row and column labels for map and apply; with duplicated labels, rendering raises
KeyError with the message "Styler.apply and .map are not compatible with non-unique index or columns."
Limits worth remembering: a Styler is for presentation, so do the calculations on the DataFrame first. Chaining operations on the
Styler after to_html has no effect, because to_html returns text. Styles that rely on :hover, title or a stylesheet work in a browser or
notebook but not in an Excel file or in an email client.
Older code and what changed
| Older statement | Status in pandas 3.1 | What to do |
|---|---|---|
|
Removed; |
|
|
Removed |
|
|
Removed |
|
|
Removed |
|
|
Removed |
|
|
Removed |
|
|
Unstyled since pandas 3.0 |
|
Styler written by hand-built |
Not needed |
|
No Typst output |
|
Use it for Typst documents |
Jinja2 is installed with pandas |
It is optional ( |
Declare it in your requirements |
Pitfalls checklist
-
The data does not change: the Styler is a view for display;
to_numpyandto_csvignore it. -
formatchanges strings, not numbers; the same applies to Excel and toto_string. -
escaperuns before the callable formatter. -
mapis per value andapplyis per column, row or frame; the function must return CSS strings of the right shape. -
Labels must be unique for
mapandapply. -
Fix the id with
set_uuidwhen the HTML is compared or when several tables share a page. -
Check the output format: LaTeX needs
convert_css=Truefor colours, and Excel needsStyler.to_excelfor any styling. -
Use colour as a second signal, never as the only one, and keep the contrast readable.