Pandas get_option() and set_option(): Read and Change Settings

Read current Pandas display options, set row and column limits and restore prior settings safely.

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

Read the current option value 🔝

get_option() returns the current setting. It may differ from the registered default or from another environment. Do not assume max_rows is always 60 or max_columns is always 20.
print("Current max_rows:", pd.get_option("display.max_rows"))
print("Current max_columns:", pd.get_option("display.max_columns"))
assert pd.get_option("display.max_rows") is None or pd.get_option("display.max_rows") >= 0

Expected output

Current max_rows: 60
Current max_columns: 0

Set max_rows to six and display the table 🔝

The original 35-row student-table and six-row display concepts are retained. Display settings change rendering, not row counts. set_option changes shared session state until changed again; try/finally restores the prior value after this example.
previous = pd.get_option("display.max_rows")
try:
    returned = pd.set_option("display.max_rows", 6)
    print("Changed max_rows:", pd.get_option("display.max_rows"))
    with pd.option_context("display.min_rows", 6, "display.max_columns", 4,
                           "display.width", 80, "display.show_dimensions", True):
        print(students)
    assert returned is None and students.shape == (35, 4)
finally:
    pd.set_option("display.max_rows", previous)
assert pd.get_option("display.max_rows") == previous

Expected output

Changed max_rows: 6
          name class  mark     sex
id                                
1   Student 01  Four    40    male
2   Student 02  Four    41  female
3   Student 03  Four    42    male
..         ...   ...   ...     ...
33  Student 33  Four    72    male
34  Student 34  Four    73  female
35  Student 35  Four    74    male

[35 rows x 4 columns]

Set max_columns to three 🔝

Retain the original column-limit example. Setting max_rows and max_columns together makes the abbreviated representation clear. Use a context for the supporting rendering options.
old_rows = pd.get_option("display.max_rows")
old_columns = pd.get_option("display.max_columns")
try:
    pd.set_option("display.max_rows", 6, "display.max_columns", 3)
    with pd.option_context("display.min_rows", 6, "display.width", 80,
                           "display.show_dimensions", True):
        print(students)
    assert pd.get_option("display.max_columns") == 3
finally:
    pd.set_option("display.max_rows", old_rows, "display.max_columns", old_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]

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

Prefer scoped settings for a temporary report 🔝

option_context changes options temporarily and restores previous values. reset_option restores defaults, which can differ from your earlier custom settings.
saved = pd.get_option("display.max_rows")
with pd.option_context("display.max_rows", 10):
    print("Temporary max_rows:", pd.get_option("display.max_rows"))
print("Previous value restored:", pd.get_option("display.max_rows") == saved)
assert pd.get_option("display.max_rows") == saved

Expected output

Temporary max_rows: 10
Previous value restored: True

Use full names and valid values 🔝

The option registry validates inputs. Unknown names raise OptionError; invalid values can raise ValueError. Do not suppress errors and assume a setting changed.
try:
    pd.get_option("display.this_option_does_not_exist")
except pd.errors.OptionError:
    print("Unknown option rejected")
else:
    raise AssertionError("Expected OptionError")
saved = pd.get_option("display.max_rows")
try:
    pd.set_option("display.max_rows", "six")
except ValueError:
    print("Invalid value rejected")
else:
    raise AssertionError("Expected ValueError")
assert pd.get_option("display.max_rows") == saved

Expected output

Unknown option rejected
Invalid value rejected

Common mistakes 🔝

get_option reads a setting, not table data. set_option returns None. Use full option names to avoid ambiguous partial matches. Unlimited display can generate excessive output for a large table; use head(), explicit selections or a controlled export instead. These settings affect the session while active, so avoid overlapping changes in concurrent code. Text print output and notebook HTML rendering can differ. See describe_option(), option_context() and reset_option().

Exercise: change precision and restore it 🔝

Read display.precision, set it to two, verify its value and restore the earlier value even if the demonstration raises an exception.

Exercise solution 🔝

Use try/finally for an intentional set_option change.
saved = pd.get_option("display.precision")
try:
    pd.set_option("display.precision", 2)
    print("Precision:", pd.get_option("display.precision"))
    assert pd.get_option("display.precision") == 2
finally:
    pd.set_option("display.precision", saved)
print("Restored:", pd.get_option("display.precision") == saved)

Expected output

Precision: 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 get_option() and set_option() 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