Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Widgets and Visualization

Tables and DataFrame Display

Show tables well in Jupyter notebooks: how pandas renders DataFrames as HTML, display options, previewing big data safely, styling with Styler, and exporting tables.

Tables are the other half of notebook output, next to charts. When you end a cell with a pandas DataFrame, the notebook shows a neat HTML table with a row index, aligned columns and shaded rows, not a block of text. This is the _repr_html_ mechanism from Rich output and display at work. In this lesson you learn how to look at data efficiently, control how tables appear, style them to highlight the story, and avoid dumping a million rows into your notebook.

pandas runs in your browser here, so the data code is runnable. The runnable cells print tables as text because the site's runner shows text output; in a real notebook the same variable displayed as the last expression becomes a rich HTML table. Styler output (colours) is HTML-only, so it is shown read-only.

Look before you load everything

Real datasets can have millions of rows. Printing them all would freeze the browser and bloat the notebook file. pandas already protects you: when a table is larger than the display limits it shows the first and last rows with ... in the middle. The standard first looks:

Call Shows
df.head() / df.tail() First or last 5 rows
df.sample(5, random_state=1) 5 random rows (seed it for repeatable output)
df.shape (rows, columns)
df.info() Column names, types, non-null counts, memory
df.describe() Count, mean, spread, quartiles for numeric columns
df.dtypes Column types
Python A first look at a small dataset

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.

In a notebook, df.head(3) as the last line of a cell would render an HTML table. The print calls above show the same data as text.

Display options

pandas keeps its display settings in pd.options.display. Set them once near the top of the notebook:

Python
import pandas as pd

pd.set_option("display.max_rows", 20)         # rows shown before truncating
pd.set_option("display.max_columns", 30)      # wide tables: show more columns
pd.set_option("display.precision", 2)         # digits after the decimal point
pd.set_option("display.float_format", "{:,.2f}".format)
pd.set_option("display.max_colwidth", 60)     # long text cells

To change a setting only inside a block, use a context manager:

Python
with pd.option_context("display.max_rows", 100):
    display(df)

Reset with pd.reset_option("display.max_rows"). The next stand-in prints a table under two different option sets, so you can see truncation and number formatting:

Python Display options change what you see

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.

Notice that options affect only display, never the data: the DataFrame still holds all 40 rows with full precision.

Showing several tables

A cell displays only its last expression. To show several tables, use display():

Python
from IPython.display import display

display(df.head(3))
display(df.describe())

Or print a Markdown heading between them with display(Markdown("### Summary")). For side-by-side tables, build an HTML string from df.to_html() and combine it in a flex container.

Styling with Styler

df.style returns a Styler object that renders the table with colours and formats. It needs the jinja2 package. Typical uses (read-only, notebook only):

Python
(df.style
   .format({"population_m": "{:.1f} M", "density": "{:,.0f}"})
   .background_gradient(subset=["density"], cmap="Blues")
   .highlight_max(subset=["area_km2"], color="gold")
   .hide(axis="index")
   .set_caption("Cities by density"))
  • .format controls number text per column.
  • .background_gradient shades cells by value, a heat map in a table.
  • .highlight_max / .highlight_min / .highlight_null mark special cells.
  • .bar draws in-cell bars.
  • .apply and .map apply your own function to colour rows or cells.

Styler changes only the output, not the data, and is best for a final report table. For hundreds of rows prefer plain tables plus a chart.

Interactive tables

Plain HTML tables do not sort or filter. For large datasets there are libraries that add this to notebooks: itables (pip install itables, then from itables import init_notebook_mode; init_notebook_mode(all_interactive=True)) renders every DataFrame as a searchable, sortable table, and JupyterLab has a built-in CSV viewer for .csv files in the file browser. Remember that interactivity needs the browser's JavaScript, so exports to PDF fall back to static tables.

Export and share tables

Python
df.to_csv("cities.csv", index=False)
df.to_excel("cities.xlsx")               # needs openpyxl
html = df.to_html(index=False)           # an HTML string
md = df.to_markdown()                    # needs tabulate; Markdown text for documents

The HTML export is useful in a stand-in for what the notebook does for you. Here we print the beginning of the HTML table of a tiny DataFrame, which is exactly what _repr_html_ returns (plus a style block):

Python What the notebook receives: the HTML of a table

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.

Good habits for tables in notebooks

  1. Never print a whole large DataFrame. Use head, sample or aggregation.
  2. Seed samples (random_state=1) so a re-run shows the same rows.
  3. Format for the reader: thousands separators, sensible decimals, units in the headers.
  4. Put the table near the sentence that explains it, using a Markdown cell (see Cell types and Markdown).
  5. Remember outputs are stored in the file: a 5,000-row table inflates the notebook and may leak personal data. Check before you share.
  6. Use an index that means something (df.set_index("city")) so rows are easy to read.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a DataFrame at the end of a cell look like a styled table instead of text?

    pandas implements _repr_html_, and the front end prefers HTML over plain text.
  2. 2. What do pandas display options like display.max_rows change?

    Options affect display only; the DataFrame keeps all rows and full precision.
  3. 3. Which call gives a repeatable random preview of a DataFrame?

    sample with a fixed random_state returns the same rows each time.
  4. 4. You want to display two DataFrames from one cell. What do you do?

    Only the last expression is shown automatically; display() can show any number of objects.

Summary

  • DataFrames are shown as HTML tables through _repr_html_; large frames are truncated automatically.
  • Preview with head, tail, sample, shape, info and describe instead of printing everything.
  • pd.set_option and pd.option_context control display only, not the data.
  • Use display() to show several tables from one cell.
  • df.style (Styler) formats and colours tables for reports; itables adds sorting and search.
  • Outputs are stored in the notebook, so keep tables small and free of sensitive data.

Next: Interactive charts and progress bars