Retrieve a fixed-size page by supplying the page's starting offset and row count.
Pagination
Polars · Module
Select a row slice from a Polars DataFrame using a starting offset and optional length. Negative offsets are supported, and a missing length selects through the final row.
Call slice with a starting row offset and optionally a length to obtain a row subset as a new DataFrame. The offset may be negative, and omitting the length selects from that offset through the end.
DataFrame.slice(offset: int, length: int | None = None) → DataFrame| Name | Type | Description |
|---|---|---|
offset | int | Start index; negative indexing is supported. |
length | int | None | Length of the slice. If None, selects all rows starting at the offset. |
DataFrame containing the selected row slice.
DataFrame.slice extracts a row-oriented subset from the current DataFrame.offset can address rows relative to the DataFrame's end.length parameter controls the number of rows returned.None for length does not select zero rows; it means selection continues from the offset to the end.import polars as pl
df = pl.DataFrame({"value": [10, 20, 30, 40]})
print(df.slice(1, 2))
print(df.slice(-2))Creates a DataFrame, selects two rows starting at index 1, then selects all rows from the second-to-last row onward.
Pagination
Tail selection
Remainder processing
DataFrame.slice do, and what arguments does it accept?DataFrame.slice takes an integer offset and an optional integer length, returning a DataFrame containing the selected rows. The offset is the starting index, and a None length extends selection to the end.
Follow-up: How would you select the final five rows? Use df.slice(-5) or df.slice(-5, 5), depending on whether an explicit length is preferred.
slice select rows relative to the end?Negative offsets are supported, so the starting position can be counted from the end of the DataFrame. The length still controls how many rows are selected when it is provided.
Follow-up: What happens if the requested range extends past the available rows? The resulting slice contains the rows available within the DataFrame rather than requiring the range to fit exactly.
DataFrame.slice return?The method returns a DataFrame, preserving the DataFrame-oriented result rather than returning a Series or scalar. For example, df.slice(1, 2) returns two rows beginning at offset one.
Follow-up: When would iter_slices be a better fit? Use it when processing a DataFrame as an iterator of row chunks rather than obtaining one selected DataFrame.
polars.DataFrame.iter_slicespolars.LazyFrame.slice