[Python] Select the first and last row per group in Polars dataframe

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use polars dataframe where I would like to select the first and last row per group. Here is a simple example selecting the first row per group:

    import polars as pl

    df = pl.DataFrame(
    {
    "a": [1, 2, 2, 3, 4, 5],
    "b": [0.5, 0.5, 4, 10, 14, 13],
    "c": [True, True, True, False, False, True],
    "d": ["Apple", "Apple", "Apple", "Banana", "Banana", "Banana"],
    }
    )
    result = df.group_by("d", maintain_order=True).first()
    print(result)


    Output:

    shape: (2, 4)
    ┌────────┬─────┬──────┬───────┐
    │ d ┆ a ┆ b ┆ c │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ i64 ┆ f64 ┆ bool │
    ╞════════╪═════╪══════╪═══════╡
    │ Apple ┆ 1 ┆ 0.5 ┆ true │
    │ Banana ┆ 3 ┆ 10.0 ┆ false │
    └────────┴─────┴──────┴───────┘


    This works good and we can use .last to do it for the last row. But how can we combine these in one group_by?

    Continue reading...

Compartilhe esta Página