df.style returns a pandas Styler that controls how a DataFrame is displayed: .format() for number formats, .background_gradient() for heatmap coloring, .highlight_max() for standout values, and .map() or .apply() for your own rules. It changes only the output, never the data.
Quick Example
import numpy as np
import pandas as pd
rng = np.random.default_rng(55)
regions = ["Northeast", "Southeast", "Midwest", "Southwest", "West"]
sales = pd.DataFrame(
{
"revenue": rng.uniform(180_000, 620_000, 5).round(-2),
"growth": rng.uniform(-0.08, 0.22, 5).round(3),
"margin": rng.uniform(0.12, 0.41, 5).round(3),
"orders": rng.integers(900, 4200, 5),
},
index=pd.Index(regions, name="region"),
)
styled = (
sales.style
.format({"revenue": "${:,.0f}", "growth": "{:+.1%}", "margin": "{:.1%}", "orders": "{:,}"})
.background_gradient(subset=["revenue"], cmap="Blues")
.bar(subset=["orders"], color="#fbbf24", vmin=0)
.map(lambda v: "color: #b91c1c; font-weight: bold" if v < 0 else "", subset=["growth"])
.set_caption("Q3 sales by region")
)
styled

In a Jupyter or VS Code notebook, putting styled on the last line of a cell renders the table. The images here were rendered from the Styler's HTML, so your notebook's fonts and spacing will look a little different. The code targets pandas 2.1 or later (tested on 3.0), and background_gradient needs Matplotlib installed.
The df.style Methods You'll Use Most
| Method | What it does |
|---|---|
format() |
Number, date, and text display formats |
background_gradient() |
Colors cell backgrounds by value |
text_gradient() |
Colors the text by value |
highlight_max(), highlight_min() |
Marks the largest or smallest values |
highlight_between(), highlight_null() |
Marks a range or missing values |
bar() |
Draws data bars inside cells |
map() |
Applies your CSS rule cell by cell |
apply() |
Applies your CSS rule to a column, row, or whole table |
set_table_styles() |
CSS for headers, rows, and borders |
hide(), set_caption() |
Hides the index or columns, adds a title |
Most of them accept subset to limit which columns or rows are affected. Each call returns the Styler, so they chain.
Format Numbers, Currency, and Percentages
Pass format a dictionary of column names to format strings or functions. na_rep sets the text for missing values.
messy = sales.copy()
messy.loc["Midwest", "growth"] = np.nan
formatted = (
messy.style
.format({"revenue": lambda v: f"${v / 1000:,.1f}k", "growth": "{:+.1%}",
"margin": "{:.0%}", "orders": "{:,}"}, na_rep="n/a")
)
formatted

The underlying values keep full precision. To change them for real, use df.round() or df.astype() instead.
Heatmap Colors with background_gradient
By default each column is colored on its own scale (axis=0). Set axis=None to use one scale across the whole table, or axis=1 to compare along each row.
monthly = pd.DataFrame(
(rng.normal(100, 18, (5, 6))
+ np.arange(6) * 6 + np.array([30, 0, -15, 5, 18])[:, None]).round().astype(int),
index=regions, columns=["Apr", "May", "Jun", "Jul", "Aug", "Sep"],
)
heat = monthly.style.background_gradient(cmap="YlGnBu", axis=None)
heat

Text switches to white on dark cells automatically. Use vmin and vmax to keep colors consistent between tables, and low or high to pad the range so the extremes aren't as saturated. For a chart-style version with a colorbar, see Seaborn heatmaps.
Highlight the Max and Min Values
With the default axis=0, these find the largest and smallest value in each column.
highlighted = (
monthly.style
.highlight_max(axis=0, color="#bbf7d0")
.highlight_min(axis=0, color="#fecaca")
)
highlighted

Ties are all highlighted, as in August, where Southwest and West share the top value of 150.
Conditional Formatting: map vs apply
mapcalls your function with one value and expects one CSS string. The quick example uses it to turn negative growth red.applycalls your function with a Series (a column, or a row whenaxis=1) and expects a list of CSS strings of the same length.
To color a whole row based on one column, use apply with axis=1:
def flag_row(row):
style = "background-color: #fef3c7" if row["margin"] < 0.15 else ""
return [style] * len(row)
rows = (
sales.style
.apply(flag_row, axis=1)
.format({"revenue": "${:,.0f}", "growth": "{:+.1%}", "margin": "{:.1%}", "orders": "{:,}"})
)
rows

Styler.applymap was renamed to Styler.map in pandas 2.1 and removed in 3.0. If old code raises AttributeError: 'Styler' object has no attribute 'applymap', change the method name.
Data Bars Around Zero
bar(align="zero") starts each bar at zero. Pass two colors for negative and positive values, and symmetric vmin and vmax to keep zero in the middle.
change = pd.DataFrame({"change": [0.14, -0.06, 0.03, -0.11, 0.09]}, index=regions)
bars = (
change.style
.format("{:+.0%}")
.bar(subset=["change"], align="zero", color=["#f87171", "#34d399"], vmin=-0.15, vmax=0.15,
props="width: 16em;")
)
bars

Style Headers and Rows with CSS
set_table_styles takes CSS selectors, which covers anything that isn't tied to a value.
css = (
sales.style
.format({"revenue": "${:,.0f}", "growth": "{:+.1%}", "margin": "{:.1%}", "orders": "{:,}"})
.set_table_styles([
{"selector": "thead th",
"props": "background-color: #1e293b; color: white;"},
{"selector": "tbody tr:nth-child(even)",
"props": "background-color: #f1f5f9;"},
{"selector": "tbody th", "props": "text-align: left;"},
])
)
css

Export a Styled Table to HTML or Excel
html = styled.to_html() # string with a <style> block and a <table>
styled.to_html("sales.html", doctype_html=True) # complete web page
to_excel writes cell colors and font styles to a workbook. It needs openpyxl.
styled.to_excel("sales.xlsx", engine="openpyxl")
Excel export doesn't carry over everything: formats set with .format() and the bars from .bar() are dropped. For Excel number formats, add them as CSS, for example .map(lambda v: "number-format: 0.0%", subset=["margin"]).
Pandas has no built-in "save as PNG". Options are a browser screenshot of the HTML, the third-party dataframe_image package, or drawing the table as a graphic.
Practical Tips
- A Styler isn't a DataFrame. Do your filtering and sorting first, and call
.stylelast. The original is still available asstyled.data. - Large tables make huge HTML. Style a
head()or an aggregated summary. - Use
.hide(axis="index")to drop the index in reports. - When a reader needs to compare many values at a glance, a chart may beat a table. See plotting DataFrame columns as lines.