You can set the number of rows displayed in a Polars DataFrame using polars.Config. There are two main ways to do this:
Globally (Persistent): Changes the default display behavior for all subsequent DataFrame prints.
Temporarily (Context Manager): Changes the display behavior only within a specific with block.
Let's look at examples for both.
First, let's create a sample DataFrame with more rows than the default display limit:
python
import polars as pl
import sys
# Create a sample DataFrame with 25 rows
data = {
"id": range(25),
"value": [f"item_{i}" for i in range(25)],
"score": [i * 1.5 for i in range(25)]
}
df = pl.DataFrame(data)
print("--- Original DataFrame (Default Display) ---")
print(df)
You'll notice the output is truncated, usually showing the first few and last few rows, with ... in the middle.
1. Global (Persistent) Change: pl.Config.set_tbl_rows()
This method modifies the global Polars configuration.
python
# Set the number of rows to display to 15
pl.Config.set_tbl_rows(15)
print("\n--- Displaying 15 rows (Global Setting) ---")
print(df)
# To display all rows, set it to a very large number
# or use sys.maxsize for the theoretical maximum
pl.Config.set_tbl_rows(sys.maxsize)
print("\n--- Displaying all rows (Global Setting) ---")
print(df)
# Reset to default (usually around 10-20, depending on Polars version)
# You can set it back to a smaller number like 10, or restore all defaults.
pl.Config.set_tbl_rows(10) # Or pl.Config.restore_defaults() to reset all config options
2. Temporary (Context Manager): with pl.Config(tbl_rows=...)
This is useful when you want to change the display settings only for a specific print statement or a block of code, without affecting subsequent prints.
python
print("\n--- Temporary Display with 5 rows ---")
with pl.Config(tbl_rows=5):
print(df)
print("\n--- Temporary Display with all rows (using context manager) ---")
# You can set it to a very large number or sys.maxsize for temporary "show all"
with pl.Config(tbl_rows=sys.maxsize):
print(df)
print("\n--- Back to Global Setting (currently 10 rows) ---")
# After the 'with' block, the setting reverts to the global default/setting
print(df)
Other Useful Display Options:
While focused on rows, it's good to know about other related display settings in pl.Config:
set_tbl_width(width: int): Sets the maximum width of the table display (useful for many columns). Use sys.maxsize or a large number for "no limit".
set_fmt_str_lengths(length: int): Sets the maximum length of string data displayed in cells.
set_float_precision(precision: int): Sets the number of decimal places for float display.
set_thousands_separator(sep: str): Sets the separator for thousands in numerical display.
restore_defaults(): Resets all Polars display configurations to their original default values.
Choose the method that best suits your needs: global for consistent behavior during a session, or temporary for one-off display adjustments.