Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 64 ยท Visualisation

Styling and Displaying Tables

Control how a DataFrame prints. Use display options, number formatting, to_string, option_context and the Styler class for conditional formatting.

Numbers are only useful when people can read them. By default pandas prints a DataFrame with six or seven digits after the decimal point, hides rows in the middle of long tables and cuts off wide ones. This lesson shows how to control that: global display options, formatting numbers into readable text, the to_string() method for plain-text reports and the Styler class that powers colored tables in notebooks.

All the plain-text tools here run in the browser editors. Styler produces HTML and needs the Jinja2 package, so its examples are shown as read-only code.

flowchart LR
    A["DataFrame (numbers)"] --> B["display options<br/>how pandas prints it"]
    A --> C["formatting<br/>numbers become text"]
    A --> D["to_string / to_csv<br/>plain text output"]
    A --> E["Styler<br/>HTML with colors"]

Four ways to present the same data. Only the first three change nothing in the data itself; the Styler returns a separate view for display.

Display options

pandas keeps its printing settings in a registry of options. Read one with pd.get_option(), change it with pd.set_option(). The names you will meet most are:

Option What it controls
display.max_rows How many rows print before the middle is replaced by ...
display.max_columns The same for columns
display.precision Digits after the decimal point for floats
display.float_format A function that formats every float
display.width The target line width in characters
display.max_colwidth The longest text shown in a cell before it is cut
Python Changing display options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With max_rows set to 6, pandas shows the first three and last three rows and a ... row. Display options never change the data, only how it is shown. In a script that sets them at the top, every later print(df) follows them, which can be surprising in other cells; reset one with pd.reset_option("display.max_rows").

Temporary settings with option_context

To change options for a single print, use pd.option_context() as a with block. The options return to their old values when the block ends, even if an error occurs.

Python option_context for a one-off view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Inside the block the table is short and rounded to one digit. Afterwards the normal settings are back, which is why head(2) prints with six decimals again. Prefer option_context over set_option in shared code.

Formatting numbers

display.float_format accepts any function that turns a float into text. A common choice is a thousands separator with two decimals:

Python
pd.set_option("display.float_format", "{:,.2f}".format)

Setting this affects every float in every table. That is convenient for a report, but it also means a column of tiny rates like 0.0003 prints as 0.00. For finer control, format columns individually and keep the numbers numeric underneath. to_string() accepts a formatters dictionary for exactly that.

Python Per-column formatting with to_string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

index=False removes the row labels. Each formatter is a function or a format-spec string method; "{:.1%}".format turns 0.2315 into 23.2%. The last lines confirm that report still holds real numbers: only the printed text changed. Never overwrite a numeric column with formatted strings if you plan to calculate with it again.

to_string and friends

to_string() returns the table as a plain string with no truncation at all, which makes it the right tool for logs and reports. Useful arguments are max_rows, columns, na_rep (text for missing values), float_format, justify and header.

Python to_string options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For other plain formats you already know to_csv() and to_json() from Writing and Formatting Data. to_markdown() produces a Markdown table; it needs the optional tabulate package. The section on exporting tables below runs it, together with to_html and to_latex.

Rounding is not formatting

df.round(2) changes the values, while precision and formatters change only the display. Use round() when the rounded number should be the number you work with from now on (money, for example). Use formatting when you only want a nicer print and want to keep full precision for later calculations. Mixing the two up leads to totals that are off by a cent.

Conditional formatting with Styler

df.style returns a Styler, an object that wraps the DataFrame and can attach CSS styles to cells. In a notebook the Styler displays as a colored HTML table. You describe the look with methods, and they chain:

Python
styled = (
    sales.style
    .format({"revenue": "${:,.0f}", "margin": "{:.1%}"})
    .background_gradient(subset=["revenue"], cmap="Blues")
    .highlight_max(subset=["margin"], color="gold")
    .bar(subset=["units"], color="#8fbf8f")
    .set_caption("Sales by product")
)
styled.to_html()   # the HTML string; in a notebook, just evaluating `styled` shows it

Some methods you will use often:

  • .format() sets the displayed text per column, like the formatters above.
  • .background_gradient() colors cells by value.
  • .highlight_max(), .highlight_min() and .highlight_null() mark special cells.
  • .bar() draws in-cell bars.
  • .map(func) applies a function to every cell that returns a CSS string, and .apply(func, axis=...) does the same per row or column. In pandas 3, Styler.map replaced the old applymap.
  • .hide(axis="index") hides the row labels.
  • .to_html() and .to_latex() export the result (see the exporting section below).

Styler needs the Jinja2 package (pip install jinja2) and, for gradients, matplotlib. The editors here cannot display HTML output, so treat these examples as reference. The idea itself works on any machine: a Styler never changes the DataFrame; it only describes how to show it.

The idea behind conditional formatting

Conditional formatting means "look decides on value". You can practise the logic without HTML. This stand-in builds a flag column with the same kind of rule you would give to Styler:

Python Rules for highlighting, as plain text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Series.map() applies the function to every value. This is the same logic that Styler.map() would run, except that Styler returns CSS such as "background-color: gold" instead of a text marker. The numeric DataFrame scores stays untouched; only a copy was converted to text.

Exporting tables to HTML, LaTeX and Markdown

A table often has to leave Python: onto a web page, into an e-mail, into a LaTeX paper or into a README. pandas has an exporter for each, and each one is a method that returns a string (or writes a file when you pass a path).

Note: to_html needs nothing extra. Styler and to_latex need the jinja2 package, and to_markdown needs tabulate. The example below installs them with micropip in the browser; on your computer use pip install jinja2 tabulate.

to_html: a table for a web page

df.to_html() returns an HTML <table>. The options control the details: index=False drops the index, classes="..." adds CSS classes to the <table> tag, table_id sets an id, float_format formats numbers, na_rep shows a symbol for missing values, columns selects columns and border=0 removes the default border attribute. By default text is escaped (escape=True), so < in your data cannot break the page.

Styler.to_html: conditional formatting with CSS

The Styler you met above produces HTML with an embedded <style> block and one id per cell, so highlights survive when you paste the result into a page or an e-mail. In a Jupyter notebook you do not call it: evaluating df.style... as the last line of a cell shows the styled table directly, because the notebook asks the object for its HTML.

to_latex and to_markdown

df.style.to_latex() writes a tabular environment (with hrules=True for the professional-looking booktabs lines; \toprule needs the booktabs package in your LaTeX preamble). The older df.to_latex() also exists and is handy when you do not need styling. df.to_markdown() writes a pipe table that GitHub, GitLab and most documentation tools render; tablefmt="github" and floatfmt=".1f" tweak it.

Python One table, four outputs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the first output: the <A4> in the product name was escaped to &lt;A4&gt;, which is what you want for data you do not control. Pass escape=False only for text you trust. Also notice that qty printed as 10.00 and 10.000000: one missing value turned the column into floats, so float_format applied. Convert it with astype("Int64") first if you want whole numbers. The Styler HTML contains its own CSS, so to show it on a web page you can write the string to a file, or insert it into a template.

Styling the exported table with CSS

to_html puts only structure in the table. The look comes from your stylesheet, which targets the classes and the id you passed:

HTML
<style>
  table.striped { border-collapse: collapse; font-family: system-ui, sans-serif; }
  table.striped th, table.striped td { padding: 6px 12px; text-align: right; }
  table.striped thead th { background: #1f2937; color: white; }
  table.striped tbody tr:nth-child(even) { background: #f3f4f6; }
  #prices td:first-child { text-align: left; font-weight: 600; }
</style>

Because pandas writes <thead>, <tbody>, <th> and <td>, plain CSS selectors are enough for striped rows, a dark header and per-column alignment. For a Styler table you can add the same kind of rule from Python with set_table_styles:

Python
styled.set_table_styles([
    {"selector": "th", "props": [("background-color", "#1f2937"), ("color", "white")]},
    {"selector": "td", "props": [("padding", "6px 12px")]},
])

Tip: For e-mails, prefer the Styler output: many mail clients drop <style> blocks, and Styler can inline its per-cell rules when you convert the HTML with a tool such as premailer. For web pages, plain to_html plus your site's stylesheet keeps the page light and consistent.

Tips for readable tables

  • Align decimals and use thousands separators, so the eye can compare magnitudes.
  • Show units in the column names (revenue_usd, temp_c) or in formatted values.
  • Show percentages as percentages, not as 0.2315.
  • Keep display settings in one place at the top of a script or in an option_context.
  • Do not store formatted text back into the data. Format at the last step before output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does pd.set_option("display.precision", 2) change?

    Display options affect printing only. The underlying floats keep full precision.
  2. 2. When is pd.option_context(...) better than pd.set_option(...)?

    option_context restores the previous values when the with block ends, so it does not leak settings into other code.
  3. 3. Why is it usually a bad idea to replace a numeric column with strings like "$1,200.00"?

    Text values cannot be used in arithmetic. Format at the end, for example with to_string(formatters=...), and keep the numbers numeric.
  4. 4. What does df.style return?

    Styler wraps the DataFrame and builds styled output such as HTML. The DataFrame itself is not changed.

Summary

  • Display options (max_rows, max_columns, precision, float_format) change how pandas prints, never the data.
  • Use pd.option_context() for temporary settings.
  • to_string() returns the full table as text and accepts formatters, na_rep, float_format, index=False and more.
  • round() changes values; formatting changes only the display.
  • df.style builds formatted, colored HTML tables (it needs Jinja2), chaining .format(), .background_gradient(), .highlight_max(), .bar() and .map().
  • to_html (with classes, table_id, escape), Styler.to_html, to_latex and to_markdown export a table as a string for pages, papers and READMEs; style the HTML with your own CSS.
  • Keep numbers numeric and format only at the last step.

Next: Memory Usage and Smaller Dtypes