# How to Style a Pandas DataFrame with df.style

> Pandas df.style tutorial: format numbers, add background_gradient and data bars, highlight max and min values, style rows with apply and cells with map, and export to HTML or Excel.

Source: https://www.pythoncharts.com/pandas/pandas-style-dataframe/ | Published: 2026-11-26 | Author: Alex Scott | Category: Pandas | Tags: pandas, df.style, styler, conditional-formatting, background_gradient, tables

`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

```python
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
```

![Styled pandas table of sales by region with currency and percent formats, a blue gradient on revenue, orange data bars on orders, and negative growth in bold red](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-quick-example.png)

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.

```python
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
```

![Pandas table with revenue shown in thousands, signed percentages, whole-number margins, and n/a for a missing growth value](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-format.png)

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.

```python
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
```

![Monthly sales table colored as a heatmap on one scale, from pale yellow for the low of 72 in April to dark blue for the high of 167 in September](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-gradient.png)

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](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/).

## Highlight the Max and Min Values

With the default `axis=0`, these find the largest and smallest value in each column.

```python
highlighted = (
    monthly.style
    .highlight_max(axis=0, color="#bbf7d0")
    .highlight_min(axis=0, color="#fecaca")
)
highlighted
```

![Monthly sales table with each month's highest value shaded green and lowest value shaded red](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-highlight-max-min.png)

Ties are all highlighted, as in August, where Southwest and West share the top value of 150.

## Conditional Formatting: map vs apply

- `map` calls your function with **one value** and expects one CSS string. The quick example uses it to turn negative growth red.
- `apply` calls your function with a **Series** (a column, or a row when `axis=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`:

```python
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
```

![Sales table with the Midwest and West rows shaded yellow because their margin is under 15 percent](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-rows.png)

`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.

```python
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
```

![Table of percent changes by region with green data bars extending right for gains and red bars extending left for losses](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-bars.png)

## Style Headers and Rows with CSS

`set_table_styles` takes CSS selectors, which covers anything that isn't tied to a value.

```python
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
```

![Pandas table with a dark header row, white header text, and alternating light gray row stripes](https://www.pythoncharts.com/pandas/pandas-style-dataframe/images/pandas-style-dataframe-css.png)

## Export a Styled Table to HTML or Excel

```python
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`.

```python
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 `.style` last. The original is still available as `styled.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](https://www.pythoncharts.com/pandas/multiple-columns-line-chart-pandas/).

## Similar Topics

- [How to Create Heatmaps in Seaborn](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/)
- [How to Generate PDF Data Reports with Embedded Python Charts](https://www.pythoncharts.com/python/generate-pdf-data-reports-python/)
- [How to Switch Pandas Default Plotting Backend to Plotly](https://www.pythoncharts.com/pandas/pandas-plotly-backend/)
