[Python] Replace last two row values in a grouped polars DataFrame

Discussão em 'Python' iniciado por Stack, Novembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    I need to replace the last two values in the value column of a pl.DataFrame with zeros, whereby I need to group_by the symbol column.

    import polars as pl

    df = pl.DataFrame(
    {"symbol": [*["A"] * 4, *["B"] * 4], "value": range(8)}
    )

    shape: (8, 2)
    ┌────────┬───────┐
    │ symbol ┆ value │
    │ --- ┆ --- │
    │ str ┆ i64 │
    ╞════════╪═══════╡
    │ A ┆ 0 │
    │ A ┆ 1 │
    │ A ┆ 2 │
    │ A ┆ 3 │
    │ B ┆ 4 │
    │ B ┆ 5 │
    │ B ┆ 6 │
    │ B ┆ 7 │
    └────────┴───────┘


    Here is my expected outcome:

    shape: (8, 2)
    ┌────────┬───────┐
    │ symbol ┆ value │
    │ --- ┆ --- │
    │ str ┆ i64 │
    ╞════════╪═══════╡
    │ A ┆ 0 │
    │ A ┆ 1 │
    │ A ┆ 0 │<-- replaced
    │ A ┆ 0 │<-- replaced
    │ B ┆ 4 │
    │ B ┆ 5 │
    │ B ┆ 0 │<-- replaced
    │ B ┆ 0 │<-- replaced
    └────────┴───────┘

    Continue reading...

Compartilhe esta Página