[Python] Possible to calculate counts and percentage in one chain using polars?

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

  1. Stack

    Stack Membro Participativo

    From seeing some of the other polars answers it seems most things can be complete in a single chain. Is that possible with the below example? Any simplifications possible?

    import polars as pl
    scores = pl.DataFrame({
    'zone': ['North', 'North', 'North', 'South', 'East', 'East', 'East', 'East'],
    'score': [78, 39, 76, 56, 67, 89, 100, 55]
    })

    cnt = scores.group_by("zone").len()
    cnt.with_columns(
    (100 * pl.col("len") / pl.col("len").sum())
    .round(2)
    .cast(str)
    .str.replace(r"$", "%")
    .alias("perc")
    )


    shape: (3, 3)
    ┌───────┬─────┬───────┐
    │ zone ┆ len ┆ perc │
    │ --- ┆ --- ┆ --- │
    │ str ┆ u32 ┆ str │
    ╞═══════╪═════╪═══════╡
    │ South ┆ 1 ┆ 12.5% │
    │ East ┆ 4 ┆ 50.0% │
    │ North ┆ 3 ┆ 37.5% │
    └───────┴─────┴───────┘

    Continue reading...

Compartilhe esta Página