Styling & Formatting Output

Reviewed & published by Brayan K

Output formatting is the set of tools that control how a DataFrame looks when you print or export it — adjusting display options, rounding numbers, emitting Markdown, and adding colour with the Styler — without ever changing the underlying data.

Part of the free Pandas course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

You will tune pd.options.display, round and format numbers, export with to_markdown() and to_string(), and apply the .style API's format, background_gradient, and highlight_max for notebooks.

What You'll Learn in This Lesson

1 Display Options & Rounding

When pandas prints a large frame it truncates with .... pd.set_option() raises those limits, and a global display.float_format controls decimal places everywhere. None of this touches the data — it only changes what you see. For a one-off, .round(n) returns a rounded copy.

import pandas as pd

pd.set_option("display.max_rows", None)        # show every row
pd.set_option("display.float_format", "{:.2f}".format)  # 2 dp

df = pd.DataFrame({"x": [1.23456, 2.5, 3.14159]})
df.round(2)        # a rounded copy: 1.23, 2.50, 3.14
import pandas as pd

df = pd.DataFrame({"product": ["a", "b", "c"],
                   "price":   [1.23456, 19.999, 3.1]})

# Round to a clean 2 decimal places (returns a copy)
clean = df.round(2)
print(clean.to_string(index=False))

# ✅ Expected output:
# product  price
#       a   1.23
#       b  20.00
#       c   3.10

2 to_string() and to_markdown() Exports

to_string() renders the whole DataFrame as plain text with no truncation — great for logs and console scripts. to_markdown() produces a Markdown table you can paste into GitHub, docs, or a chat message. Both return a string, so you can print it or write it to a file.

df = pd.DataFrame({"name": ["Ann", "Bo"], "score": [91, 84]})

print(df.to_string(index=False))
# name  score
#  Ann     91
#   Bo     84

print(df.to_markdown(index=False))
# | name   |   score |
# |:-------|--------:|
# | Ann    |      91 |
# | Bo     |      84 |
import pandas as pd

df = pd.DataFrame({"name": ["Ann", "Bo", "Cy"],
                   "score": [91, 84, 77]})

# Full text dump, no truncation, no index column
print(df.to_string(index=False))

# ✅ Expected output:
# name  score
#  Ann     91
#   Bo     84
#   Cy     77

3 The .style API — Colour for Notebooks

df.style returns a Styler that renders rich HTML in Jupyter and browsers. .format() sets per-column number formatting, .background_gradient() shades cells by value, and .highlight_max() marks the largest value in each column. These affect presentation only — the data is untouched.

styled = (
    df.style
      .format({"price": "{:.2f}"})       # 2 decimals in one column
      .background_gradient(cmap="Blues") # shade by value
      .highlight_max(color="gold")       # mark the biggest
)
# In a notebook this displays a coloured HTML table.
# .to_html() turns it into an HTML string.
import pandas as pd

df = pd.DataFrame({"city": ["NYC", "LA", "SF"],
                   "sales": [120, 95, 140]})

# Build a Styler and render it to an HTML string
styled = df.style.format({"sales": "{:.0f}"}).highlight_max(
    subset="sales", color="gold")

html = styled.to_html()
print("Styler:", type(styled).__name__)
print("highlight present:", "gold" in html)

# ✅ Expected output:
# Styler: Styler
# highlight present: True
import pandas as pd

df = pd.DataFrame({"team": ["A", "B", "C"],
                   "avg":  [3.14159, 2.71828, 1.61803]})

# 🎯 YOUR TURN:
# Round the "avg" column to 2 decimal places for a tidy print.
# Replace ___ with the number of decimals.

print(df.round(___).to_string(index=False))

# Expected output:
# team  avg
#    A 3.14
#    B 2.72
#    C 1.62

! Common Errors (And How to Fix Them)

❌ Expecting .style colours in a terminal

A Styler only renders in HTML environments:

print(df.style.highlight_max())   # ❌ prints a Styler object, no colours

✅ Fix: in plain text, round and use to_string:

print(df.round(2).to_string())   # ✅

❌ Thinking round() changes the original

df.round(2)
print(df)        # ❌ still full precision; round returned a copy

✅ Fix: keep the returned copy:

df = df.round(2)   # ✅ reassign to keep the rounding

🎯 Mini Challenge: Make a Report-Ready Table

Polish a small results table for sharing.

import pandas as pd

df = pd.DataFrame({
    "region": ["North", "South", "East"],
    "rate":   [12.345, 9.8, 15.0],
    "growth": [0.1234, 0.205, 0.0876],
})

report = df.round({"rate": 1, "growth": 3})
print(report.to_string(index=False))

# A Styler highlight for a notebook (presentation only)
html = df.style.highlight_max(subset="rate", color="gold").to_html()
print("max highlighted:", "gold" in html)

# ✅ Expected output:
# region  rate  growth
#  North  12.3   0.123
#  South   9.8   0.205
#   East  15.0   0.088
# max highlighted: True

❓ Frequently Asked Questions

Lesson complete — your tables look professional!

You can tune display options, round and format numbers, export with to_markdown() and to_string(), and dress up notebook tables with the .style API — all without altering the data.

Practice quiz

Which call stops pandas truncating rows when it prints?

  • pd.show_all_rows()
  • pd.set_option('display.max_rows', None)
  • df.expand()
  • pd.no_truncate()

Answer: pd.set_option('display.max_rows', None). Setting display.max_rows to None tells pandas to print every row.

What does df.round(2) return?

  • None
  • The original frame modified in place
  • A rounded copy of the DataFrame
  • Only the rounded column

Answer: A rounded copy of the DataFrame. round returns a new rounded copy; the original is unchanged.

Which method renders the whole DataFrame as plain text with no truncation?

  • df.to_markdown()
  • df.to_html()
  • df.show()
  • df.to_string()

Answer: df.to_string(). to_string() dumps the full table as untruncated plain text.

Which method produces a Markdown table you can paste into GitHub?

  • df.to_markdown()
  • df.to_text()
  • df.to_md()
  • df.markdown()

Answer: df.to_markdown(). to_markdown() emits a Markdown-formatted table (needs tabulate).

What does df.style return?

  • A plain string
  • A Styler object that renders HTML
  • A new DataFrame
  • A list of colours

Answer: A Styler object that renders HTML. df.style returns a Styler that renders rich HTML in notebooks.

Where do .style colours actually render?

  • In a plain terminal
  • In log files
  • In HTML environments like Jupyter and browsers
  • In CSV exports

Answer: In HTML environments like Jupyter and browsers. The Styler needs an HTML environment to show colours.

Does the .style API change the underlying data?

  • Yes, it rounds the values
  • Yes, it drops columns
  • Only for numeric columns
  • No, it only affects presentation

Answer: No, it only affects presentation. Styling affects the visual HTML only; the data is untouched.

Which Styler method shades cells by their value?

  • background_gradient()
  • color_scale()
  • shade_by()
  • heat()

Answer: background_gradient(). .background_gradient() shades each cell based on its value.

Which package does to_markdown() rely on?

  • numpy
  • openpyxl
  • tabulate
  • jinja2

Answer: tabulate. to_markdown() needs the tabulate package installed.

How do you set a global 2-decimal display for floats?

  • df.round('all')
  • pd.decimals(2)
  • df.format(2)
  • pd.set_option('display.float_format', '{:.2f}'.format)

Answer: pd.set_option('display.float_format', '{:.2f}'.format). display.float_format controls how floats print everywhere.

Continue this course

Frequently asked questions

How do I stop pandas truncating my DataFrame with ...?

Raise the display limits with pd.set_option('display.max_rows', None) and pd.set_option('display.max_columns', None). These settings change how pandas prints, not the data itself. Use pd.reset_option('all') to return to the defaults afterward.

What is the difference between formatting and the .style API?

round() and pd.set_option('display.float_format', ...) change the plain-text numbers you print in any environment. The .style API produces a rich HTML table with colours, gradients, and highlights that renders in Jupyter notebooks and browsers, but not in a plain terminal.

When should I use to_markdown() or to_string()?

to_string() prints the entire DataFrame as text with nothing truncated, which is ideal for logs and scripts. to_markdown() emits a Markdown table you can paste into GitHub, documentation, or chat. Both return strings, so you can save them to a file.

Does the .style API change my underlying data?

No. Methods like background_gradient, highlight_max, and format only affect the visual presentation of an HTML Styler object. The original DataFrame and its values stay exactly the same, so styling is always safe to apply.