Pandas option_context(): Temporary Display Settings

Temporarily control table display, restore previous options and practise nested contexts and Excel input.

Create a portable student table 🔝

The original tutorial displays 35 student rows after reading Excel with id as the index. This replacement uses explicitly synthetic records so the examples run without a local D: drive. It has four data columns after moving id into the index, correcting the original five-column description.
import pandas as pd
students = pd.DataFrame({"id": range(1, 36),
    "name": [f"Student {i:02d}" for i in range(1, 36)],
    "class": ["Four"] * 35, "mark": [40 + i for i in range(35)],
    "sex": ["female" if i % 2 else "male" for i in range(35)]}).set_index("id")
print(students.head(3))
assert students.shape == (35, 4)

Expected output

          name class  mark     sex
id                                
1   Student 01  Four    40    male
2   Student 02  Four    41  female
3   Student 03  Four    42    male

Temporarily set max_rows and max_columns 🔝

Use with pd.option_context() with option/value pairs. The original settings of six rows and three columns are retained. A truncated display does not remove rows or columns from the data. More on available option descriptions.
before_rows = pd.get_option("display.max_rows")
before_columns = pd.get_option("display.max_columns")
with pd.option_context("display.max_rows", 6, "display.min_rows", 6,
                       "display.max_columns", 3, "display.width", 80,
                       "display.show_dimensions", True):
    print(students)
    assert pd.get_option("display.max_rows") == 6
print("Rows restored:", pd.get_option("display.max_rows") == before_rows)
print("Columns restored:", pd.get_option("display.max_columns") == before_columns)
assert students.shape == (35, 4)

Expected output

          name  ...     sex
id              ...        
1   Student 01  ...    male
2   Student 02  ...  female
3   Student 03  ...    male
..         ...  ...     ...
33  Student 33  ...    male
34  Student 34  ...  female
35  Student 35  ...    male

[35 rows x 4 columns]
Rows restored: True
Columns restored: True

Restore the previous value, not a hard-coded default 🔝

The original output showed 60 after the block, but restoration depends on the value before entering the block. This nested example demonstrates restoration to 12, then restoration to the original setting.
original = pd.get_option("display.max_rows")
with pd.option_context("display.max_rows", 12):
    with pd.option_context("display.max_rows", 6):
        print("Inner:", pd.get_option("display.max_rows"))
    print("Outer restored:", pd.get_option("display.max_rows"))
print("Original restored:", pd.get_option("display.max_rows") == original)
assert pd.get_option("display.max_rows") == original

Expected output

Inner: 6
Outer restored: 12
Original restored: True

Restore options when the block raises an exception 🔝

Context cleanup runs when an exception leaves the with block. Catch the exception outside the block and confirm restoration.
saved = pd.get_option("display.max_columns")
try:
    with pd.option_context("display.max_columns", 2):
        raise ValueError("Synthetic review failure")
except ValueError as error:
    print(str(error))
print("Restored after failure:", pd.get_option("display.max_columns") == saved)
assert pd.get_option("display.max_columns") == saved

Expected output

Synthetic review failure
Restored after failure: True

Retain the Excel input workflow 🔝

For your own file, read_excel(path, index_col="id") preserves the original import idea. Here an embedded sample creates a temporary workbook, reads it and cleans it automatically. Requires openpyxl. You can also use the original student Excel exercise.
from tempfile import TemporaryDirectory
from pathlib import Path
with TemporaryDirectory(dir=".") as folder:
    workbook = Path(folder) / "student.xlsx"
    students.reset_index().to_excel(workbook, index=False, engine="openpyxl")
    loaded = pd.read_excel(workbook, index_col="id")
    print("Imported shape:", loaded.shape)
    pd.testing.assert_frame_equal(loaded, students)
print("Temporary workbook removed:", not workbook.exists())

Expected output

Imported shape: (35, 4)
Temporary workbook removed: True

Use an explicit text representation for an export 🔝

Display options affect rendering, not the underlying values. For a specific report, to_string() can take its own options. Avoid printing an entire large dataset merely to inspect it.
text = students.head(2).to_string(index=False)
print(text)
assert students.index.name == "id" and len(students) == 35

Expected output

      name class  mark    sex
Student 01  Four    40   male
Student 02  Four    41 female

Common mistakes 🔝

Use full option names such as display.max_rows; short regular-expression matches can be ambiguous. max_rows and min_rows interact when truncating. option_context restores previous settings; reset_option resets defaults. Display settings affect shared Pandas state during the block, so avoid overlapping contexts in concurrent execution. print text and notebook HTML may render differently. Never infer missing records from an abbreviated preview. See get_option()/set_option() and reset_option().

Exercise: a temporary column limit 🔝

Temporarily set display.max_columns to two, inspect its value within the block, then verify the earlier value is restored.

Exercise solution 🔝

Capture the previous value before entering the context.
previous = pd.get_option("display.max_columns")
with pd.option_context("display.max_columns", 2):
    print("Inside:", pd.get_option("display.max_columns"))
print("Restored:", pd.get_option("display.max_columns") == previous)
assert pd.get_option("display.max_columns") == previous

Expected output

Inside: 2
Restored: True

Practice in Google Colab 🔝

Open in Google Colab View on GitHub

Run examples in order, inspect the table display and try the exercise. Save a copy to keep edits.

Reference: Pandas option_context() documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer