polars.Expr.interpolate#

Expr.interpolate(method: InterpolationMethod = 'linear') Expr[source]#

Fill nulls with linear interpolation over missing values.

Can also be used to regrid data to a new grid - see examples below.

Parameters:
method{‘linear’, ‘linear’}

Interpolation method

Examples

>>> # Fill nulls with linear interpolation
>>> df = pl.DataFrame(
...     {
...         "a": [1, None, 3],
...         "b": [1.0, float("nan"), 3.0],
...     }
... )
>>> df.select(pl.all().interpolate())
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪═════╡
│ 1   ┆ 1.0 │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2   ┆ NaN │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 3   ┆ 3.0 │
└─────┴─────┘
>>> df_original_grid = pl.DataFrame(
...     {
...         "grid_points": [1, 3, 10],
...         "values": [2.0, 6.0, 20.0],
...     }
... )  # Interpolate from this to the new grid
>>> df_new_grid = pl.DataFrame({"grid_points": range(1, 11)})
>>> (
...     df_new_grid.join(
...         df_original_grid, on="grid_points", how="left"
...     ).with_column(pl.col("values").interpolate())
... )
shape: (10, 2)
┌─────────────┬────────┐
│ grid_points ┆ values │
│ ---         ┆ ---    │
│ i64         ┆ f64    │
╞═════════════╪════════╡
│ 1           ┆ 2.0    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2           ┆ 4.0    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 3           ┆ 6.0    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 4           ┆ 8.0    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ ...         ┆ ...    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 7           ┆ 14.0   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 8           ┆ 16.0   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 9           ┆ 18.0   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 10          ┆ 20.0   │
└─────────────┴────────┘