cycle

cycle(expr, offset=1)

Return a Polars expression that cycles the rows by a given offset.

You may consider rechunking the result of cycle() using pl.Expr.rechunk() for better performance.

Parameters

expr :

A single Polars expression to apply the cycling operation on.

offset : int = 1

The number of rows to cycle by. Positive values shift rows downward, and negative values shift rows upward.

Returns

: pl.Expr

A Polars expression with values cyclically shifted.

Examples

DataFrame Context

Cycle downward by 2 rows:

import polars as pl
import turtle_island as ti

pl.Config.set_fmt_table_cell_list_len(10)
df = pl.DataFrame({"x": [1, 2, 3, 4]})
df.with_columns(ti.cycle(pl.col("x"), 2).alias("cycle"))
shape: (4, 2)
xcycle
i64i64
13
24
31
42

Cycle upward by 4 rows (no visible change due to full cycle):

df.with_columns(ti.cycle(pl.col("x"), -4).alias("cycle"))
shape: (4, 2)
xcycle
i64i64
11
22
33
44

List Namespace Context

In the list namespace, it may be easier to think of each row as an element in a list. Conceptually, you’re working with a pl.Series, where each row corresponds to one item in the list.

Cycle downward by 2 elements:

df2 = pl.DataFrame(
    {
        "x": [[1, 2, 3, 4], [5, 6, 7, 8]],
        "y": [[9, 10, 11, 12], [13, 14, 15, 16]],
    }
)
df2.with_columns(pl.all().list.eval(ti.cycle(pl.element(), 2)))
shape: (2, 2)
xy
list[i64]list[i64]
[3, 4, 1, 2][11, 12, 9, 10]
[7, 8, 5, 6][15, 16, 13, 14]