[Python] How to do a horizontal forward_fill in Polars?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    I am wondering if there's a way to do forward filling by columns in polars.

    df = pl.DataFrame(
    {
    "id": ["NY", "TK", "FD"],
    "eat2000": [1, 6, 3],
    "eat2001": [-2, None, 4],
    "eat2002": [None, None, None],
    "eat2003": [-9, 3, 8],
    "eat2004": [None, None, 8]
    }
    ); df


    shape: (3, 6)
    ┌─────┬─────────┬─────────┬─────────┬─────────┬─────────┐
    │ id ┆ eat2000 ┆ eat2001 ┆ eat2002 ┆ eat2003 ┆ eat2004 │
    │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ i64 ┆ i64 ┆ f64 ┆ i64 ┆ i64 │
    ╞═════╪═════════╪═════════╪═════════╪═════════╪═════════╡
    │ NY ┆ 1 ┆ -2 ┆ null ┆ -9 ┆ null │
    │ TK ┆ 6 ┆ null ┆ null ┆ 3 ┆ null │
    │ FD ┆ 3 ┆ 4 ┆ null ┆ 8 ┆ 8 │
    └─────┴─────────┴─────────┴─────────┴─────────┴─────────┘


    I would like to do the equivlanet of .ffill(axis=1) in pandas.

    pl.from_pandas(df.to_pandas().ffill(axis=1))


    shape: (3, 6)
    ┌─────┬─────────┬─────────┬─────────┬─────────┬─────────┐
    │ id ┆ eat2000 ┆ eat2001 ┆ eat2002 ┆ eat2003 ┆ eat2004 │
    │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ i64 ┆ f64 ┆ f64 ┆ i64 ┆ f64 │
    ╞═════╪═════════╪═════════╪═════════╪═════════╪═════════╡
    │ NY ┆ 1 ┆ -2.0 ┆ -2.0 ┆ -9 ┆ -9.0 │
    │ TK ┆ 6 ┆ 6.0 ┆ 6.0 ┆ 3 ┆ 3.0 │
    │ FD ┆ 3 ┆ 4.0 ┆ 4.0 ┆ 8 ┆ 8.0 │
    └─────┴─────────┴─────────┴─────────┴─────────┴─────────┘

    Continue reading...

Compartilhe esta Página