polars.Expr.list.shift#

Expr.list.shift(n: int | IntoExprColumn = 1) Expr[source]#

将列表值按给定的索引数移动。

Parameters:
n

向前移动的索引数量。如果传递了负值,则值将向相反方向移动。

注释

此方法类似于SQL中的LAG操作,当n的值为正时。当n的值为负时,它类似于LEAD

示例

默认情况下,列表值会向前移动一个索引。

>>> df = pl.DataFrame({"a": [[1, 2, 3], [4, 5]]})
>>> df.with_columns(shift=pl.col("a").list.shift())
shape: (2, 2)
┌───────────┬──────────────┐
│ a         ┆ shift        │
│ ---       ┆ ---          │
│ list[i64] ┆ list[i64]    │
╞═══════════╪══════════════╡
│ [1, 2, 3] ┆ [null, 1, 2] │
│ [4, 5]    ┆ [null, 4]    │
└───────────┴──────────────┘

传递一个负值以向相反方向移动。

>>> df.with_columns(shift=pl.col("a").list.shift(-2))
shape: (2, 2)
┌───────────┬─────────────────┐
│ a         ┆ shift           │
│ ---       ┆ ---             │
│ list[i64] ┆ list[i64]       │
╞═══════════╪═════════════════╡
│ [1, 2, 3] ┆ [3, null, null] │
│ [4, 5]    ┆ [null, null]    │
└───────────┴─────────────────┘